Python itertools.combinations_with_replacement 未返回所有组合
Python itertools.combinations_with_replacement not returning all combinations
我写了一个简单的python程序:
#!/usr/bin/env python3.5
import sys, itertools
sCharacters = '123'
for iCombinationLength in range(0, len(sCharacters)+1):
for aCombination in itertools.combinations_with_replacement(sCharacters, iCombinationLength):
print(''.join(aCombination))
这将输出以下内容:
1
2
3
11
12
13
22
23
33
111
112
113
122
123
133
222
223
233
333
然而,如果它是数字 1 2 和 3 的所有组合,则需要包括:
311
312
313
321
322
323
331
332
333
正如您在上面看到的那样,事实并非如此。我已经看到其他帖子给出了 combinations_with_replacement 函数,作为获取传入字符的所有可能组合的解决方案。但这似乎并没有发生。我在这里做错了什么,我怎样才能得到字符变量中字符的所有可能组合?
感谢您的宝贵时间 ;-)
"combinations" 是一个不区分顺序的术语;如果你有113
,那么你不需要131
或311
,因为它们都是相同的"combination"(如果输入序列为combinations_with_replacement
是唯一的,您可以在转换为 collections.Counter
后将输出视为所有唯一值;无论顺序如何,两个 1
和一个 3
只是 collections.Counter({1: 2, 3:1})
).
如果您想要 combinations_with_replacement
的顺序敏感版本(因此 113
、131
和 311
都是单独的输出),请使用 itertools.product
repeat
参数(由于 product
的设计,repeat
必须通过关键字传递,它采用可变长度的位置参数):
sCharacters = '123'
for iCombinationLength in range(0, len(sCharacters)+1):
for aCombination in itertools.product(sCharacters, repeat=iCombinationLength):
print(''.join(aCombination))
我写了一个简单的python程序:
#!/usr/bin/env python3.5
import sys, itertools
sCharacters = '123'
for iCombinationLength in range(0, len(sCharacters)+1):
for aCombination in itertools.combinations_with_replacement(sCharacters, iCombinationLength):
print(''.join(aCombination))
这将输出以下内容:
1
2
3
11
12
13
22
23
33
111
112
113
122
123
133
222
223
233
333
然而,如果它是数字 1 2 和 3 的所有组合,则需要包括:
311
312
313
321
322
323
331
332
333
正如您在上面看到的那样,事实并非如此。我已经看到其他帖子给出了 combinations_with_replacement 函数,作为获取传入字符的所有可能组合的解决方案。但这似乎并没有发生。我在这里做错了什么,我怎样才能得到字符变量中字符的所有可能组合?
感谢您的宝贵时间 ;-)
"combinations" 是一个不区分顺序的术语;如果你有113
,那么你不需要131
或311
,因为它们都是相同的"combination"(如果输入序列为combinations_with_replacement
是唯一的,您可以在转换为 collections.Counter
后将输出视为所有唯一值;无论顺序如何,两个 1
和一个 3
只是 collections.Counter({1: 2, 3:1})
).
如果您想要 combinations_with_replacement
的顺序敏感版本(因此 113
、131
和 311
都是单独的输出),请使用 itertools.product
repeat
参数(由于 product
的设计,repeat
必须通过关键字传递,它采用可变长度的位置参数):
sCharacters = '123'
for iCombinationLength in range(0, len(sCharacters)+1):
for aCombination in itertools.product(sCharacters, repeat=iCombinationLength):
print(''.join(aCombination))