Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The simple and elegant way to express multiple for loop in python?

Tags:

python

I have below code, would like to know what is the best simple and elegant way to express multiple for loop?

for x in range (10):
    for y in range (10):
        for z in range(10):
            if x+y+z=10:
                print (x,y,z)

Thanks in advance!

like image 218
Coeus Wang Avatar asked Nov 24 '25 23:11

Coeus Wang


1 Answers

from itertools import product

for x, y, z in product(range(10), range(10), range(10)):
    if x + y + z == 10:
        print(x, y, z)

To remove range(10) duplication use this:

for x, y, z in product(range(10), repeat=3):

EDIT: as Tomerikoo pointed out - in this specific case the code will be more flexible if you don't unpack the tuple:

for numbers in product(range(10), repeat=3):
    if sum(numbers) == 10:
        print(*numbers)
like image 59
RafalS Avatar answered Nov 27 '25 14:11

RafalS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!