在所有可能的位置添加位

时间:2013-09-24 10:23:42

标签: python

我有一个列表,我希望通过在所有可能的位置添加x 1和0来使所有列表成为可能。例如,假设x = 2和

l=[0,1]

首先,我们只需在开头提供[0,0,0,1][0,1,0,1][1,0,0,1][1,1,0,1]的所有可能的长度为2的列表。然后我们在开始时放置0或1,在位置2放置0或1,得到[0,0,0,1][0,0,1,1][1,0,0,1][1,0,1,1]

然后,我们将对列表中可能插入两个位的每个可能位置执行相同的操作。当然会有很多重复,但我可以使用set删除它们。

另一个例子,这次是x = 1

l=[1,1]

完整输出应为[0,1,1], [1,0,1], [1,1,0], [1,1,1]

有没有聪明的方法来做到这一点?

3 个答案:

答案 0 :(得分:3)

IIUC,你可以使用这样的东西:

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 tup

给出了

>>> 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)])

答案 1 :(得分:1)

我认为你想要的是itertools.product

import itertools
x = 2
l = [0, 1]
print list(itertools.product(l + [0, 1], repeat=len(l)+x))

答案 2 :(得分:1)

# input
l=[1,1]
x=1

# create bit combinations that may be added to l
import itertools
combos = itertools.product([0,1], repeat=x)

# iterate through positions (k) and bit combinations (c) with
# a single generator expression. Might be more memory efficient
# if combos would only be generated directly here
set(tuple(l)[:k] + c + tuple(l)[k:] for c in combos for k in range(len(l)+1))

# returns
# set([(0, 1, 1), (1, 1, 1), (1, 1, 0), (1, 0, 1)])