Generating binary combinations with fixed places (Python)

Viewed 181

I want to generate a list of tuples of all possible combinations of 0/1 of size n=16, but where some positions are fixed. So some positions are fixed a 0 or 1 (x,x,x,x,1,x,x,x,0,0,x,x,x,x,x,x). I know we can use itertools to generate all possible combinations without any fixed places:

import itertools

permutations = list(itertools.product([0, 1], repeat=16))

I was thinking of generating all combinations with repeat=13 and then inserting the fixed places, but this seems too cumbersome to me. Are there easier and faster ways to achieve this?

2 Answers

Just a little change based on itertools.product:

def custom_product(f, repeat=0):
    return itertools.product(*[f.get(i, [0, 1]) for i in range(repeat)])

fixed = {4: [1], 8: [0], 9: [0]}
print(*custom_product(fixed, 16), sep="\n")

And the format of result is the same as your expected.

Well I like recursion:

n_bits = 8
fixed = {0:"0",
        3:"1"}

def permut_fixed(n_bits, fixed):
    def aux(base, bits_left):
        if bits_left<=0:
            return [base]
        if len(base) in fixed:
            return aux(base+fixed[len(base)], bits_left-1)
        else:
            return [*aux(base+"0", bits_left-1), *aux(base+"1", bits_left-1)]
    return aux("", n_bits)

print(permut_fixed(n_bits, fixed))
# ['00010000', '00010001', ..., '01111011', '01111100', '01111101', '01111110', '01111111']
print(len(permut_fixed(n_bits, fixed)))
# 64 which is 2**6 and we have 6 slots to fill
Related