➽ 可以想要列出所有排列的字母或數字,用空格分開
Python Code:
import itertools
list1=input('請輸入n個要排列的數,以空格分開==> ').split()
w=[]
w=[str(x) for x in list1] #將輸入的字串改成整數
nums = itertools.permutations(w) # 它是tuple
for x in nums:
print(x)
# 以上是有用itertools工具
#以下是副函式1
def perm_1(head,tail=''):
if len(head)==0:
print(tail)
else:
for i in range(len(head)):
perm_1(head[0:i]+head[i+1:],tail+head[i])
perm_1(w)
#以下是副函式2
def perm_2(a,k=0):
if k==len(a):
print(a)
else:
for i in range(k,len(a)):
a[k],a[i]=a[i],a[k]
perm_2(a,k+1)
a[k],a[i]=a[i],a[k]
perm_2(w)
#以下是副函式3
def perm_3(clst):
if len(clst)==1:
return [clst[0]]
results = []
for idx, c in enumerate(clst):
results += [c+substr for substr in perm_3(clst[:idx] + clst[idx+1:])]
return results
print(perm_3(w))
沒有留言:
張貼留言