Tuesday, 24 January 2017

python - How to get all combination of n binary value?




In Python, how can I get all combinations of n binary values 0 and 1?




For example, if n = 3, I want to have



[ [0,0,0], [0,0,1], [0,1,0], [0,1,1], ... [1,1,1] ]  #total 2^3 combinations


How can I do this?


Answer



Use itertools.product




import itertools
lst = list(itertools.product([0, 1], repeat=3))


This will yield a list of tuples (see here)



You can easily change this to use a variable repeat:



n = 3
lst = list(itertools.product([0, 1], repeat=n))



If you need a list of lists, then you can use the map function (thanks @Aesthete).



lst = map(list, itertools.product([0, 1], repeat=n))


Or in Python 3:



lst = list(map(list, itertools.product([0, 1], repeat=n)))

# OR
lst = [list(i) for i in itertools.product([0, 1], repeat=n)]


Note that using map or a list comprehension means you don't need to convert the product into a list, as it will iterate through the itertools.product object and produce a list.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...