Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten large loop stacks?

Let's say I wanted to get all the possible combinations of three binary digits, i.e:

0,0,0
0,0,1
0,1,0
0,1,1
1,0,0
1,0,1
1,1,0
1,1,1

I could do something like this:

p = []
for a in range(2):
    for b in range(2):
        for c in range(2):
           p.append([a,b,c])

print p

But what if I wanted to define a function that returns the possiblities for n numbers of binary digits? i.e. How can I stack the for loops dynamically?

like image 593
Alex Coplan Avatar asked Jan 18 '26 04:01

Alex Coplan


2 Answers

from itertools import product
product(range(2), repeat=3)
like image 64
Danra Avatar answered Jan 19 '26 17:01

Danra


Take a look at itertools.product.

like image 31
Roman Bodnarchuk Avatar answered Jan 19 '26 17:01

Roman Bodnarchuk



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!