【问题标题】:generating all permutations of 2 ones and 3 zeroes with itertools使用 itertools 生成 2 个 1 和 3 个 0 的所有排列
【发布时间】:2012-02-17 10:47:33
【问题描述】:

可能是基本的,但在任何其他问题中都找不到。 我试过了:

print ["".join(seq) for seq in itertools.permutations("00011")]

但是有很多重复,似乎 itertools 不理解所有的零并且所有的都是相同的......

我错过了什么?

编辑:

哎呀。感谢 Gareth,我发现这个问题是重复的:permutations with unique values。 没有关闭它,因为我认为我对问题的措辞更清楚。

【问题讨论】:

标签: python combinatorics itertools


【解决方案1】:
list(itertools.combinations(range(5), 2))

返回一个包含 10 个位置的列表,其中两个位置可以在五位数以内(其他位置为零):

[(0, 1),
 (0, 2),
 (0, 3),
 (0, 4),
 (1, 2),
 (1, 3),
 (1, 4),
 (2, 3),
 (2, 4),
 (3, 4)]

对于有 2 个 1 和 13 个 0 的情况,请使用:

list(itertools.combinations(range(5), 2))

返回一个包含 105 个位置的列表。而且它比您原来的解决方案要快得多。

现在的功能:

def combiner(zeros=3, ones=2):
    for indices in itertools.combinations(range(zeros+ones), ones):
        item = ['0'] * (zeros+ones)
        for index in indices:
            item[index] = '1'
        yield ''.join(item)

print list(combiner(3, 2))

['11000',
 '01100',
 '01010',
 '01001',
 '00101',
 '00110',
 '10001',
 '10010',
 '00011',
 '10100']

这需要 14.4µs。

list(combiner(13, 2))

返回 105 个元素需要 134µs。

【讨论】:

  • 思考问题的非常聪明的方法。
【解决方案2】:
set("".join(seq) for seq in itertools.permutations("00011"))

【讨论】:

  • 太棒了!但是当我尝试 2 个 1 和 13 个 0(C(15,2)=105 个选项)时,python 需要永远计算这 105 个选项......为什么这么慢?
  • 那是因为这个策略贯穿所有15个! = 1,307,674,368,000 个输入排列。
  • 呸。有什么更有效的吗?可能缺少itertools的一些组合能力,这不可能是正确的......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多