Skip to main content
 首页 » 编程设计

Python itertools.combinations_with_replacement 不返回所有组合

2024年10月17日7shihaiming

我写了一个简单的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 函数作为获取传入字符的所有可能组合的解决方案。但这似乎并没有发生。我在这里做错了什么,我怎样才能得到字符变量中字符的所有可能组合?

感谢您的宝贵时间 ;-)

请您参考如下方法:

“组合”是一个不区分顺序的术语;如果你有 113,那么你就不需要 131 或 311,因为它们都是相同的“组合”(如果输入combinations_with_replacement 的序列是唯一的,您可以在转换为 collections.Counter 后将输出视为所有唯一值;无论顺序如何,两个 1 s 和 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))