Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binary list contains all possible options by knowing its length in python

Tags:

python

i am trying to get a binary list contains all possibilities by providing the length of these possible lists , now i found a solution but it is not very handy to be used in other functions.

example : i want a list of lists each one represents one binary option of four digits.

if the length is 4 then the result should be the following.

[[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 1, 1], [0, 1, 0, 0], [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 1], [1, 0, 1, 0], [1, 0, 1, 1], [1, 1, 0, 0], [1, 1, 0, 1], [1, 1, 1, 0], [1, 1, 1, 1]]

what i have done is by the following code:

>>> [[a, b, c, d] for a in [0,1] for b in [0,1] for c in [0,1] for d in [0,1]]

Now , i am looking for a way that by knowing the length of each member binary list we can generate the big list without the need to type manually [ a, b, c, d] , so if is possible to generate the list by a function lets say L_set(4) we get the list above . and if we type L_set(3) we get the following:

[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]

and by typing L_set(2) we get :

[[0, 0], [0, 1], [1, 0], [1, 1]]

and so on.

After spending few hours i felt stuck here in this point , i hope that some of you can help.

Thanks

like image 579
mazlor Avatar asked Jun 13 '26 10:06

mazlor


2 Answers

Looks like a job for itertools.product:

>>> import itertools
>>> n = 4
>>> list(itertools.product((0,1), repeat=n))
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]
like image 156
arshajii Avatar answered Jun 18 '26 00:06

arshajii


I think the itertools module in the standard library can help, in particular the product function.

http://docs.python.org/2/library/itertools.html#itertools.product

for x in itertools.product( [0, 1] , repeat=3 ):
    print x

gives

 (0, 0, 0)
 (0, 0, 1)
 (0, 1, 0)
 (0, 1, 1)
 (1, 0, 0)
 (1, 0, 1)
 (1, 1, 0)
 (1, 1, 1)

the repeat parameter is the length of each combination in the output

like image 30
Steve Allison Avatar answered Jun 18 '26 00:06

Steve Allison



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!