【问题标题】:Generate unique combinations of non-unique elements生成非独特元素的独特组合
【发布时间】:2020-12-15 23:50:49
【问题描述】:

假设我有一个字符串aaaaaaaabbbbccdefg,其中包含许多重复元素。如何有效地生成所有可能的元素组合?他们的顺序无关紧要。

我的情况应该产生9*5*3*2*2*2*2=2160可能性:a可以选择0到8次,b0到4次,c0到2次和def , g 全部 0 或 1 次。

我试过itertools.combinations,但它不能有效地处理重复项,只返回一些固定长度的组合。 powerset 配方解决了后者,但不是第一个问题。

【问题讨论】:

    标签: python combinations


    【解决方案1】:

    最后我自己在 Code Review 上找到了the solution。诀窍是使用collections.Counter

    from collections import Counter
    from itertools import product
    
    s = Counter('aaaaaaaabbbbccdefg')  # Or Counter({'a': 8, 'b': 4, 'c': 2, 'd': 1, 'e': 1, 'f': 1, 'g': 1})
    gen = [''.join(Counter(dict(zip(s.keys(), p))).elements()) for p in product(*[range(n + 1) for n in s.values()])]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      • 2018-01-06
      相关资源
      最近更新 更多