【问题标题】:maximum number combinations最大数量组合
【发布时间】:2010-11-26 00:50:46
【问题描述】:

我正在尝试使用从 0 到 9 的所有数字生成一组四个数字中所有可能的数字组合的列表。

我已经接近了,但输出并未显示从 0000 一直到 9999 的所有可能组合。

关于以下代码为何丢弃某些组合的任何线索?

def permgen(项目,n): 如果 n==0:产量 [] 别的: 对于我在范围内(长度(项目)): 对于 cc 在 permgen(items[:i]+items[i+1:],n-1): 产量 [items[i]]+cc 如果 __name__=="__main__": 对于 c in permgen(['0','1','2','3','4','5','6','7','8','9'],4):打印''.join(c)

【问题讨论】:

  • 一个数字可以出现多次吗? 1234 与 1243 的组合不同吗?
  • 是的,这将是两个独立的组合。

标签: python combinations


【解决方案1】:

如果你有 python 2.6,为什么不使用itertools.combinations

from itertools import combinations
combinations(range(10), 4)

【讨论】:

    【解决方案2】:

    这一行:

    for cc in permgen(items[:i]+items[i+1:],n-1):
    

    您基本上是在说“获取一个数字,而不是从 ir 添加另一个 不同,重复 n 次,然后返回这些数字的列表。这将为您提供没有数字出现的数字不止一次。如果您将该行更改为:

    for cc in permgen(items,n-1):
    

    然后你得到所有的组合。

    【讨论】:

      【解决方案3】:

      看看itertools' combinatoric generators

      >>> from itertools import combinations, permutations, product
      >>> def pp(chunks):
      ...     print(' '.join(map(''.join, chunks)))
      ...
      >>> pp(combinations('012', 2))
      01 02 12
      >>> pp(permutations('012', 2))
      01 02 10 12 20 21
      >>> pp(product('012', repeat=2))
      00 01 02 10 11 12 20 21 22
      >>> from itertools import combinations_with_replacement
      >>> pp(combinations_with_replacement('012', 2))
      00 01 02 11 12 22
      

      combinations_with_replacement 在 Python 3.1(或 2.7)中可用。

      看来itertools.product 最适合你的任务。

      【讨论】:

        【解决方案4】:
        int ra;
        for(ra=0,ra<10000;ra++) printf("%04u\n",ra);
        

        【讨论】:

        • Python 编译器肯定会在这段代码中度过一天......;-)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-08
        • 1970-01-01
        • 2018-10-20
        • 2021-04-11
        • 1970-01-01
        • 1970-01-01
        • 2014-09-14
        相关资源
        最近更新 更多