如何生成整数的 n 位组合?
How to generate unto n digit combinations of an integer?
我正在尝试在 python 中创建一个程序,它为给定的数字
生成所有可能的组合(不重复)
如果输入是“123”,输出应该是
123,132,213,231,312,321
12,13,21,23,31,32
1,2,3
我当前的代码是
import itertools
a=[1,2,3]
for i in range(1,len(a)+1):
print(list(itertools.combinations(a,i)))
您可以使用 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']
考虑不重复所有可能的组合和输出。
from itertools import permutations
N = str(int(input()))
for length in range(len(N),0,-1):
currOrder = []
for order in permutations(N,length):
comb = ''.join(order)
if comb not in currOrder:
currOrder.append(comb)
print(*currOrder,sep=",")
我正在尝试在 python 中创建一个程序,它为给定的数字
生成所有可能的组合(不重复)如果输入是“123”,输出应该是
123,132,213,231,312,321
12,13,21,23,31,32
1,2,3
我当前的代码是
import itertools
a=[1,2,3]
for i in range(1,len(a)+1):
print(list(itertools.combinations(a,i)))
您可以使用 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']
考虑不重复所有可能的组合和输出。
from itertools import permutations
N = str(int(input()))
for length in range(len(N),0,-1):
currOrder = []
for order in permutations(N,length):
comb = ''.join(order)
if comb not in currOrder:
currOrder.append(comb)
print(*currOrder,sep=",")