Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using two for loops in python

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.

like image 516
user127575 Avatar asked Nov 27 '22 12:11

user127575


2 Answers

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 is 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)
like image 70
Anurag Uniyal Avatar answered Dec 16 '22 01:12

Anurag Uniyal


for i in range(1, 11):
    for j in range(1, 11):
        print i * j
like image 26
Luper Rouch Avatar answered Dec 16 '22 01:12

Luper Rouch