【问题标题】:python combination with replacement not working as expected与替换的python组合没有按预期工作
【发布时间】:2020-01-30 18:57:08
【问题描述】:

我想通过使用一组允许替换的字符来生成一定长度的所有组合:

我认为itertools.combinations_with_replacement 是我需要的。所以这就是我所做的:

from itertools import combinations_with_replacement
allowed = ['0', '1', '8', '6', '9']
comb = list(combinations_with_replacement(allowed,2))

然而这样产生的组合数是 15。但它应该是 25 (5^2)。怎么回事?

编辑:

按照@Michael Bianconi 的建议,我用permutations 替换了combinations_with_replacement,但它也不起作用 - 我得到的结果集是 20,而不是 25。

【问题讨论】:

  • 组合与排列?
  • 组合,而不是排列,因为排序无关紧要。
  • 好的,因为有 15 种组合,但有 25 种排列。

标签: python-3.x combinations combinatorics


【解决方案1】:

您可能正在搜索产品:

import itertools
allowed = ['0', '1', '8', '6', '9']
product = list(itertools.product(allowed, repeat=2))
print(len(product))

25

字符串在 Python 中是可迭代的,因此您可以使用:

import itertools
for result in itertools.product('01869', repeat=2)):
    print(result)

【讨论】:

    【解决方案2】:
    00, 01, 08, 06, 09
    11, 18, 16, 19
    88, 86, 89
    66, 69
    99
    

    有 15 种可能的组合。

    【讨论】:

    • 当涉及到组合时,顺序无关紧要,96 与 69 相同。
    猜你喜欢
    • 2019-08-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 2014-02-26
    • 1970-01-01
    相关资源
    最近更新 更多