本文為大家分享了Python實(shí)現(xiàn)全排列的打印的代碼,供大家參考,具體如下
問題:輸入一個(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: <encoding name> -*- '''全排列的demoinput : 3output: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 = 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以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選