I am trying to use a nested for loop to simply add two sets of numbers together respectively.
x=[1,2,3,4]
f=[0,1,2,3]
for i in x:
for j in f:
ans = i+j
ans2 = j
print(ans,ans2)
My output is
6 5
7 5
8 5
9 5
However, I want it to be
1 0
3 1
5 2
7 3
I'm not quite sure where i'm going wrong and any help would be appreciated.
You need to use the index into x to get the appropriate value of f to use as j. You can do this by iterating over the enumerated x:
x=[1,2,3,4]
f=[0,1,2,3]
for idx, i in enumerate(x):
j = f[idx]
ans = i+j
ans2 = j
print(ans,ans2)
Alternatively you could use zip and iterate both values at once:
for i, j in zip(x, f):
ans = i+j
ans2 = j
print(ans,ans2)
In both cases the output is:
1 0
3 1
5 2
7 3
Related
You could somehow hold it in a loop after the first iteration and store it in a variable and then continue on. So that in one variable there is a standard loop and in the other a previous loop?
example:
import numpy as np
for j in np.arange(0,5):
print(j)
0
1
2
3
4
5
6
i need example
0
1 0
2 1
3 2
4 3
5 4
6 5
just save the variable you want to print next, and print it before change it with the next one
num = 0
for j in np.arange(0,5):
print(num)
num = j
import numpy as np
for j in np.arange(0,7):
if j == 0:
print(j)
continue
print(j, j-1)
Use zip and itertools.tee:
itr1, itr2 = tee(np.arange(0, 5))
i, j = next(itr1), None
print(i, j)
for i, j in zip(itr1, itr2):
print(i, j)
outputs
0 None
1 0
2 1
3 2
4 3
The question is poorly worded, but here's a good basic iteration. It keeps track of the current variable, as well as saving it.
In [161]: alist = [1,3,6,9,12]
...: blist = []
...: latest = None
...: for item in alist:
...: blist.append(item)
...: print(latest, blist[-1])
...: latest = item
...: print(blist)
None 1
1 3
3 6
6 9
9 12
[1, 3, 6, 9, 12]
In the iteration, the current value is item, the previous is latest. blist[-1] is the last added item.
for i in range(0,x):
for j in range(0,y):
if (i+j)%2 == 0:
Think of something like tossing two dices at the same time and finding if the sum on the dices is an even number but here's the catch, a dice has 6 sides but here the two can have any number of sizes, equal and not equal even!
Can anyone suggest how to merge it under one loop because I can't think of any?
based on Python combine two for loops, you can merge two for loops in a single line by importing itertools as below:
import itertools
for i, j in itertools.product(range(0,x), range(0,y)):
if (i+j)%2 == 0:
You can't get rid of the nested loop (you could hide it, like by using itertool.product, but it would still be executed somewhere, and the complexity would still be O(x * y)) but you can get rid of the condition, if you only need to generate the values of j that satisfy it, by adapting the range for j.
This way, you'll have about twice as less loops by avoiding the useless ones.
for i in range(0,x):
for j in range(i%2,y, 2):
print(i, j, i+j)
Output:
0 0 0
0 2 2
1 1 2
1 3 4
2 0 2
2 2 4
For me its much cleaner to leave it as two loops. Its much more readable and easier to understand whats happening. However you could essentially do x * y then use divmod to calculate i and j
x = 2
y = 3
for i in range(0,x):
for j in range(0,y):
print(i, j, i+j)
print("###")
for r in range(x*y):
i, j = divmod(r, y)
print(i, j, i + j)
OUTPUT
0 0 0
0 1 1
0 2 2
1 0 1
1 1 2
1 2 3
###
0 0 0
0 1 1
0 2 2
1 0 1
1 1 2
1 2 3
Hello am a beginner to python and I have been stuck at this problem for awhile now. I want to start with 2 lists:
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [a, b, c]
And write a function that will give me this output:
a
1
2
3
b
4
5
6
c
7
8
9
I have tried using nested for loops and a counter but I am unsure how to obtain the above result.
counter = 0
for i in list2:
print(i)
for j in list1:
print(j)
counter += 1
if counter == 3:
counter = 0
break
Any help would be appreciated!
Here's one possible way, closer to what you intended to write:
j = 0
for i in list2:
print(i)
for _ in range(3):
print(list1[j])
j += 1
Here's an option:
for i, v1 in enumerate(list2):
print(v1)
for v2 in list1[i*3:(i+1)*3]:
print(v2)
You don't need to make and update your own counters here. The built-in enumerate() function generates a counter for you and automatically updates it for each step of the loop. Then you can use list slicing to get the right three values of the inner list.
Try this:
for i in list2:
print(i)
# here you don't have to take it back to 0
counter = 0
for j in range(len(list1)):
# Use range to loop the list so you can cut it off later
# from the position you reach the third element
print(list1[j])
counter += 1
if counter == 3:
list1 = list1[j + 1:]
break
It outputs what you expect:
a
1
2
3
b
4
5
6
c
7
8
9
I want to print the following sequence of integers in a pyramid (odd rows sorted ascending, even rows sorted descending). If S=4, it must print four rows and so on.
Expected output:
1
3 2
4 5 6
10 9 8 7
I tried out the following code but it produced the wrong output.
S=int(input())
for i in range(1,S+1):
y=i+(i-1)
if i%2!=0:
print(*range(i,y+1))
elif i%2==0:
print(*range(y,i-1,-1))
# Output:
# 1
# 3 2
# 3 4 5
# 7 6 5 4
You need some way of either keeping track of where you are in the sequence when printing each row, generating the entire sequence and then chunking it into rows, or... (the list of possible approaches goes on and on).
Below is a fairly simple approach that just keeps track of a range start value, calculates the range stop value based on the row number, and reverses even rows.
rows = int(input())
start = 1
for n in range(1, rows + 1):
stop = int((n * (n + 1)) / 2) + 1
row = range(start, stop) if n % 2 else reversed(range(start, stop))
start = stop
print(*row)
# If rows input is 4, then output:
# 1
# 3 2
# 4 5 6
# 10 9 8 7
Using itertools.count and just reversing the sublist before printing on even rows
from itertools import count
s = 4
l = count(1)
for i in range(1, s+1):
temp = []
for j in range(i):
temp.append(next(l))
if i % 2:
print(' '.join(map(str, temp)))
else:
print(' '.join(map(str, temp[::-1])))
1
3 2
4 5 6
10 9 8 7
In C language we can use two index variable in a single for loop like below.
for (i = 0, j = 0; i < i_max && j < j_max; i++, j++)
Can some one tell how to do this in Python ?
With zip we can achieve this.
>>> i_max = 5
>>> j_max = 7
>>> for i, j in zip(range(0, i_max), range(0, j_max)):
... print str(i) + ", " + str(j)
...
0, 0
1, 1
2, 2
3, 3
4, 4
If the first answer does not suffice; to account for lists of different sizes, a possible option would be:
a = list(range(5))
b = list(range(15))
for i,j in zip(a+[None]*(len(b)-len(a)),b+[None]*(len(a)-len(b))):
print(i,j)
Or if one wants to cycle around shorter list:
from itertools import cycle
for i,j in zip(range(5),cycle(range(2)):
print(i,j)
One possible way to do that is to iterate over a comprehensive list of lists.
For example, if you want to obtain something like
for r in range(1, 3):
for c in range(5, 7):
print(r, c)
which produces
# 1 5
# 1 6
# 2 5
# 2 6
is by using
for i, j in [[_i, _j] for _i in range(1, 3) for _j in range(5, 7)]:
print(i, j)
Maybe, sometimes one more line is not so bad.
You can do this in Python by using the syntax for i,j in iterable:. Of course in this case the iterable must return a pair of values. So for your example, you have to:
define the list of values for i and for j
build the iterable returning a pair of values from both lists: zip() is your friend in this case (if the lists have different sizes, it stops at the last element of the shortest one)
use the syntax for i,j in iterable:
Here is an example:
i_max = 7
j_max = 9
i_values = range(i_max)
j_values = range(j_max)
for i,j in zip(i_values,j_values):
print(i,j)
# 0 0
# 1 1
# 2 2
# 3 3
# 4 4
# 5 5
# 6 6