Search code examples
pythonpython-3.xcombinationspython-itertoolscombinatorics

How do I get all possible orderings of 9 zeros and 9 ones using Python?


I want to end up with a list with 48 620 nested lists, containing 9 zeros and 9 ones in different orders.

from itertools import permutations

print(list(permutations('000000000111111111', r=18)))

I assume the code above works, but every 0 and 1 is treated like an individual symbol, so for every ordering I get tons of repeats:

('0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1')
('0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1')
('0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1')
('0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1')
('0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1')
('0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1')
('0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1')
('0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1')
('0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1')
('0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1')
...

So, basically, how do I shuffle a list in every possible way, excluding repeats?

I tried to use every method from itertools, but I didn't find one that specifically does what i need.


Solution

  • Where 18 is the length of the list you want to generate and 9 is how many of them should be 0:

    for x in itertools.combinations(range(18),9):
        print(tuple(('0' if i in x else '1' for i in range(18))))
    

    The idea here is to use combinations to choose the set of locations that will be 0 for each of (in your example's case) 48620 lists.