Iterate through 2 Python list and get all x to y combinations [duplicate] - python-3.x

This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
Closed 2 years ago.
I have the following two lists:
x = [1,2]
y = [4,5,6]
I want to iterate x by z.
I have a variable called code set to NONE and another variable called value also set to NONE. Here is the output I am aiming for:
1st iteration, code = 1 and value = 4
2nd iteration, code = 1 and value = 5
3rd iteration, code = 1 and value = 6
4th iteration, code = 2 and value = 4
5th iteration, code = 2 and value = 5
6th iteration, code = 2 and value = 6
Here is what I have tried:
x = [1, 2]
y = [4, 5, 6]
code = None
value = None
for x_ids, y_ids in zip(x, y):
code = x_ids
value = y_ids
print("c", code)
print("v", value)
output:
c 1
v 4
c 2
v 5
Can anyone suggest how to get the output described above?

This is one way to achieve what you're looking for:
x = [1, 2]
y = [4, 5, 6]
code = None
value = None
iter_count = 0
for x_ids in x:
code = x_ids
for y_ids in y:
iter_count += 1
value = y_ids
print('{} iteration, code = {} and value = {}'.format(iter_count, code, value))
#print(str(iter_count) + ' iteration, code = ' + str(code) + 'and value = ' + str(value))
Like discussed in the comments, this code iterates through all elements of y for every element in x. In your original code, you were iterating through both lists all at ones, using zip. Since you want to print the number of iteration too, there is a new variable, iter_count, that counts and stores those.
The code has two print statements, they print the same messages. The commented out one concatenates strings, and numbers converted to strings. The uncommented one may be less intuitive but it is often more useful and cleaner. It's worth looking at it, you can find an introduction here.
Last thing, if you need that too - to print numbers in 1st, 2nd etc. format you can use some of these approaches.

Related

How to code in such a way that you are taking an element from a list and comparing it with all other elements of another list in python

If it matches the string then increment else continue
meaning if x = ["you","me","us","then"] and y = ["hi","king","you","you","thai","you"] the code should take string you compare with all the elements in y and then increment a variable if it matches and return 3
Note: the code should not stop if it matches once with you it should search till end of the elements?
x = ["you","me","us","then"]
y = ["hi","king","you","you","thai","you"]
word_count = {}
for each_word in x :
word_count[each_word] = y.count(each_word)
print(dict)
#result : {'you': 3, 'me': 0, 'us': 0, 'then': 0}
if this is not the answer you are looking for, Please explain the question by providing sample result you are expecting.

Why does using modulus and floor division in Python return a reversed binary number?

I'm new to programming, and I don't understand why this code returns the binary number of the input.
x = int(input())
while x > 0:
print(x % 2, end='')
x = x // 2
For example, when I enter 6, I expect it to return 0 (6 % 2 = 0, 0 // 2 = 0), but it returns 011.
I stated contemplating this because, in an assignment, we're supposed to use this coding to help us reverse the output (while using a string) but I don't know how to reverse it when I don't know why it works.
The answer of 011 is correct for your code, just trace it thru. You start with 6%2 so you get a 0. Then 6 floor 2 is 3, which is then the x for the next iteration so it becomes 3%2 which is 1 and the final iteration creates the last 1. Remember that you're not changing the value of x in the print statement, it only changes in the last line.

Counting pairs of numbers that adds up to a specific value in Python

i want to count how many pairs of numbers in a list can add to a specific number, this is my code in python but the output is not what it should be
list = [1,2,3,4]
x=3
count = 0
for i in range(len(list)):
for j in range(len(list)):
if i + j == x:
count+=1
print(count)
You could simpilify your code with functions from the built-in itertools module, depending on how you would like to iterate through the list, i.e. combinations, combinations with replacements, or products.
import itertools as itt
in_list = [1,2,3,4]
tgt_num = 3
count = 0
for a,b in itt.combinations(in_list, 2): # returns 1
# for a,b in itt.combinations_with_replacement(in_list, 2): # returns 1
# for a,b in itt.product(in_list, in_list): # returns 2
if a + b == tgt_num:
count += 1
print(count)
Your code has some issues:
One is that it never directly references the items of the list. Because of this, it will only work assuming that the numbers in the list are in ascending order, each is one apart, and that it starts at 1.
Another is that it iterates through the pairs of numbers too many times.
Finally, there are some indentation issues, but I'm guessing those were just lost in the copy-paste. I tried to re-indent it, but when I ran it I got "4", when it should be "1".
Here's a version that incorporates indexing the list, which should resolve the above issues.
list = [1,2,3,4]
x = 3
count = 0
for i in range(0,len(list)):
pair1 = list[i]
pair2 = list[i+1:]
for j in range(0,len(pair2)):
if pair1 + pair2[j] == x:
count += 1
print(count)

python3 functional programming: Accumulating items from a different list into an initial value

I have some code that performs the following operation, however I was wondering if there was a more efficient and understandable way to do this. I am thinking that there might be something in itertools or such that might be designed to perform this type of operation.
So I have a list of integers the represents changes in the number of items from one period to the next.
x = [0, 1, 2, 1, 3, 1, 1]
Then I need a function to create a second list that accumulates the total number of items from one period to the next. This is like an accumulate function, but with elements from another list instead of from the same list.
So I can start off with an initial value y = 3.
The first value in the list y = [3]. The I would take the second
element in x and add it to the list, so that means 3+1 = 4. Note that I take the second element because we already know the first element of y. So the updated value of y is [3, 4]. Then the next iteration is 4+2 = 6. And so forth.
The code that I have looks like this:
def func():
x = [0, 1, 2, 1, 3, 1, 1]
y = [3]
for k,v in enumerate(x):
y.append(y[i] + x[i])
return y
Any ideas?
If I understand you correctly, you do what what itertools.accumulate does, but you want to add an initial value too. You can do that pretty easily in a couple ways.
The easiest might be to simply write a list comprehension around the accumulate call, adding the initial value to each output item:
y = [3 + val for val in itertools.accumulate(x)]
Another option would be to prefix the x list with the initial value, then skip it when accumulate includes it as the first value in the output:
acc = itertools.accumulate([3] + x)
next(acc) # discard the extra 3 at the start of the output.
y = list(acc)
Two things I think that need to be fixed:
1st the condition for the for loop. I'm not sure where you are getting the k,v from, maybe you got an example using zip (which allows you to iterate through 2 lists at once), but in any case, you want to iterate through lists x and y using their index, one approach is:
for i in range(len(x)):
2nd, using the first append as an example, since you are adding the 2nd element (index 1) of x to the 1st element (index 0) of y, you want to use a staggered approach with your indices. This will also lead to revising the for loop condition above (I'm trying to go through this step by step) since the first element of x (0) will not be getting used:
for i in range(1, len(x)):
That change will keep you from getting an index out of range error. Next for the staggered add:
for i in range(1, len(x)):
y.append(y[i-1] + x[i])
return y
So going back to the first append example. The for loop starts at index 1 where x = 1, and y has no value. To create a value for y[1] you append the sum of y at index 0 to x at index 1 giving you 4. The loop continues until you've exhausted the values in x, returning accumulated values in list y.

Convert list of integers to a single integer : ValueError

I am trying to convert a list of integers in Python into a single integer say for example [1,2,3,4] to 1234(integer). In my function, I am using following piece of code:
L = [1,2,3,4]
b = int(''.join(map(str, L)))
return b
The compiler throws a ValueError. Why so? How to rectify this issue?
You can do this like this also if that cause problems:
L = [1,2,3,4]
maxR = len(L) -1
res = 0
for n in L:
res += n * 10 ** maxR
maxR -= 1
print(res)
1234
another solution would be
L = [1,2,3,4]
digitsCounter = 1
def digits(num):
global digitsCounter
num *= digitsCounter
digitsCounter *= 10
return num
sum(map(digits, L[::-1]))
the digits() is a non pure function that takes a number and places it on place value depending on the iteration calling digits on each iteration
1. digits(4) = 4 1st iteration
2. digits(4) = 40 2nd iteration
3. digits(4) = 400 3rd iteration
when we sum up the array returned by map from the inverted list L[::-1] we get 1234 since every digit in the array is hoisted to it place value
if we choose not no invert L array to L[::-1] then we would need our digits function to do more to figure out the place value of each number in the list so we use this to take adv of language features

Resources