Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all combination of n binary value? [duplicate]

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?

like image 902
LWZ Avatar asked Feb 18 '13 08:02

LWZ


People also ask

How many possible binary combinations are there?

A binary digit is called a bit. There are two possible states in a bit, usually expressed as 0 and 1. A series of eight bits strung together makes a byte, much as 12 makes a dozen. With 8 bits, or 8 binary digits, there exist 2^8=256 possible combinations.

How many combinations of binary are there in 7 variables?

There are 128 'binary numbers' with 7 digits. For a given position, half have 0, half have 1 in that position.

How do you figure out how many bits a combination has?

There are several methods: 2^n where n is the number of bits (2^8) Each bit has 2 possibilities. Unsigned value of all 1's + 1 (255 + 1) Count up from 0 to max value (all ones) + zero.


1 Answers

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.

like image 96
Volatility Avatar answered Sep 23 '22 14:09

Volatility