Search code examples
pythonlistbinarypython-itertools

Python - Generate binary list with itertools


I want to generate the following output:

[11000] all combinations with these numbers, but no doubles

   [11000]
   [01100]
   [00110]
   [00011]
   [10100]
   .
   .
   .

But I cannot figure out how to do that. In my problem the list has 365 values with about 20 ones.


Solution

  • You have 365 possible positions to place 20 ones. So one way to approach this is making all 20-length combinations of the 365 positions.

    An example of how that could look like in code:

    from itertools import combinations
    
    n = 365
    r = 20
    
    for indexes in combinations(range(n), r):
        base = [0]*n
        for i in indexes:
            base[i] = 1
        print(base)
    

    Since this is a "n choose r" problem, you'll have lots of possible combinations! To calculate how many, use: n! / (r!(n-r)!) = 365! / (20!(365-20)!) = 426112827338828179808453831565930.