I have a list and I want to make all lists possible by adding x 1s and 0s in all possible places. For example,say x = 2 and
l=[0,1] First we just place all possible lists of length 2 at the start giving [0,0,0,1] , [0,1,0,1] , [1,0,0,1] , [1,1,0,1] . Then we place 0 or 1 at the start and 0 or 1 at position 2 giving [0,0,0,1] , [0,0,1,1] , [1,0,0,1] , [1,0,1,1] .We would then do the same for every possible pair of positions in the list where two bits can be inserted. There will of course be a lot of duplicates but I can remove those using set .
Another example, this time with x = 1
l=[1,1] The complete output should be [0,1,1], [1,0,1], [1,1,0], [1,1,1] .Is there a smart way to do this?
IIUC, you could use something like this:
from itertools import product, combinations def all_fill(source, num): output_len = len(source) + num for where in combinations(range(output_len), len(source)): # start with every possibility poss = [[0,1]] * output_len # impose the source list for w, s in zip(where, source): poss[w] = [s] # yield every remaining possibility for tup in product(*poss): yield tupwhich gives
>>> set(all_fill([1,1], 1)) set([(0, 1, 1), (1, 1, 0), (1, 1, 1), (1, 0, 1)]) >>> set(all_fill([0,1], 2)) set([(1, 0, 1, 1), (1, 1, 0, 1), (1, 0, 1, 0), (0, 1, 1, 1), (0, 1, 0, 1), (1, 0, 0, 1), (0, 0, 1, 0), (0, 1, 1, 0), (0, 1, 0, 0), (0, 0, 1, 1), (0, 0, 0, 1)])