當前位置:成語大全網 - 新華字典 - Python中用遞歸的思想求ABCDE的全排列

Python中用遞歸的思想求ABCDE的全排列

def?p(s,res=[]):

#將字符c插入到數列ar中,會有多少種排列

def?h(c,ar):

return?[ar[:i]+[c]+ar[i:]?for?i?in?range(len(ar)+1)]

#已有結果arr的基礎上,如果增加c字符,arr會變成多少種排列

def?g(c,arr,res=[]):

if?arr==res==[]:

return?[[c]]

elif?arr==[]:

return?res

else:

return?g(c,arr[1:],res+h(c,arr[0]))

#主體遞歸

if?s=='':

return?res

else:

return?p(s[1:],g(s[0],res))

if?__name__=='__main__':

s='ABCDE'

for?x?in?p(s):

print(''.join(x))