這篇文章主要介紹Python如何實(shí)現(xiàn)全排列的打印,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
問題:輸入一個(gè)數(shù)字:3,打印它的全排列組合:123 132 213 231 312 321,并進(jìn)行統(tǒng)計(jì)個(gè)數(shù)。
下面是Python的實(shí)現(xiàn)代碼:
#!/usr/bin/env python # -*- coding:-*- ''' 全排列的demo input : 3 output:123 132 213 231 312 321 ''' total = 0 def permutationCove(startIndex, n, numList): '''遞歸實(shí)現(xiàn)交換其中的兩個(gè)。一直循環(huán)下去,直至startIndex == n ''' global total if startIndex >= n: total += 1 print numList return for item in range(startIndex, n): numList[startIndex], numList[item] = numList[item], numList[startIndex] permutationCove(startIndex + 1, n, numList ) numList[startIndex], numList[item] = numList[item], numList[startIndex] n = int(raw_input("please input your number:")) startIndex = 0 total = 0 numList = [x for x in range(1,n+1)] print '*' * 20 for item in range(0, n): numList[startIndex], numList[item] = numList[item], numList[startIndex] permutationCove(startIndex + 1, n, numList) numList[startIndex], numList[item] = numList[item], numList[startIndex] print total
以上是“Python如何實(shí)現(xiàn)全排列的打印”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!