Hello, I have started to learn python recently and have a question about for loops that I was hoping someone could answer. I want to be able to print all the possible products of two numbers from one to ten. so: 2 by 2, 2 by 3, 2 by 4...2 by 10, 3 by 2, 3 by 3...3 by 10, 4 by 2, 4 by 3 etc...I would have thought the easiest way to do so would be to use two for loops but I am not sure. could anyone please tell me how this is done. thanks very much. asadm.
+2
A:
Just for fun (and the itertools-addicted SO readers) using only one for-loop:
from itertools import product
for i,j in product(xrange(1,11), xrange(1,11)):
print i*j
EDIT: using xrange as suggested by Hank Gay
wr
2009-06-23 14:07:09
Might as well use xrange if you're bringing itertools.
Hank Gay
2009-06-23 14:10:54
Fyi, product is unneeded (but meh, C loops instead of python), python has syntax for this:product(range(1,11), range(1,11)) <=> (i,j for i in range(1,11) for j in range(1,11))for x in (i*j for i in range(1,11) for j in range(1,11)): print x,
THC4k
2009-06-23 14:20:05
but then again you have >1 for-loops ;-)
wr
2009-06-23 14:22:19
+3
A:
here is another way
a = [i*j for i in xrange(1,11) for j in xrange(i,11)]
note we need to start second iterator from 'i' instead of 1, so this is doubly efficient
edit: proof that it same as simple solution
b = []
for i in range(1,11):
for j in range(1,11):
b.append(i*j)
print set(a) == set(b)
Anurag Uniyal
2009-06-23 14:26:16
rough timing show for 10000 iteration a takes .8 sec while b takes 2.5 se so abt 3 times slower b is
Anurag Uniyal
2009-06-23 14:32:35