如何生成整数的n位组合?
我正在尝试在 python 中创建一个程序,它为给定的数字生成所有可能的组合(非重复)
如果输入为“123”,则输出应为
123,132,213,231,312,321
12,13,21,23,31,32
1,2,3
123,132,213,231,312,321
12,13,21,23,31,32
1,2,3
我目前的代码是
回答
您可以使用itertools.permutations:
import itertools
def permute_all(value):
return [''.join(permutation) for i in range(len(value)) for permutation in itertools.permutations(value, i+1)]
print(permute_all('123'))
# Outputs ['1', '2', '3', '12', '13', '21', '23', '31', '32', '123', '132', '213', '231', '312', '321']