本文為大家分享了Python實現全排列的打印的代碼,供大家參考,具體如下
問題:輸入一個數字:3,打印它的全排列組合:123 132 213 231 312 321,并進行統計個數。
下面是Python的實現代碼:
#!/usr/bin/env python# -*- coding: <encoding name> -*- '''全排列的demoinput : 3output:123 132 213 231 312 321''' total = 0 def permutationCove(startIndex, n, numList): '''遞歸實現交換其中的兩個。一直循環下去,直至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 = 0total = 0numList = [x for x in range(1,n+1)]print '*' * 20for 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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林站長站。
新聞熱點
疑難解答