3

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

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

关于为什么以下代码删除某些组合的任何线索?

def permgen(项目,n):
  如果 n==0:产量 []
    别的:
        对于我在范围内(len(items)):
            对于 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)
4

4 回答 4

12

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

from itertools import combinations
combinations(range(10), 4)
于 2009-09-06T15:34:42.343 回答
4

这一行:

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

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

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

然后你得到所有的组合。

于 2009-09-06T15:40:47.293 回答
4

看看itertools 的组合生成器

>>> 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最适合您的任务。

于 2009-09-06T17:34:13.740 回答
0
int ra;
for(ra=0,ra<10000;ra++) printf("%04u\n",ra);
于 2009-09-06T15:37:13.727 回答