本文實例講述了Python全排列操作。分享給大家供大家參考,具體如下:
step 1: 列表的全排列:
這個版本比較low
# -*-coding:utf-8 -*-#!python3def permutation(li,index): for i in range(index,len(li)): if index == len(li)-1: print(li) return tmp = li[index] li[index] = li[i] li[i] = tmp permutation(li,index+1) tmp = li[index] li[index] = li[i] li[i] = tmp
調用:
permutation([1,2,3,4],0)
運行結果:
[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 3, 2, 4]
[1, 3, 4, 2]
[1, 4, 3, 2]
[1, 4, 2, 3]
[2, 1, 3, 4]
[2, 1, 4, 3]
[2, 3, 1, 4]
[2, 3, 4, 1]
[2, 4, 3, 1]
[2, 4, 1, 3]
[3, 2, 1, 4]
[3, 2, 4, 1]
[3, 1, 2, 4]
[3, 1, 4, 2]
[3, 4, 1, 2]
[3, 4, 2, 1]
[4, 2, 3, 1]
[4, 2, 1, 3]
[4, 3, 2, 1]
[4, 3, 1, 2]
[4, 1, 3, 2]
[4, 1, 2, 3]
step2: 字符串的全排列:
# -*-coding:utf-8 -*-#!python3def permutation(str): li = list(str) cnt = 0 #記錄全排列的總數 def permutation_list(index): if index == len(li) -1: nonlocal cnt cnt += 1 print(li) for i in range(index,len(li)): li[index],li[i] = li[i],li[index] permutation_list(index+1) li[index], li[i] = li[i], li[index] ret = permutation_list(0) print("共有%d中全排列" % cnt) return ret
備注:
在閉包中,內部函數依然維持了外部函數中自由變量的引用—單元。內部函數不能修改單元對象的值(但是可以引用)。若嘗試修改,則解釋器會認為它是局部變量。這類似于全局變量和局部變量的關系。如果在函數內部修改全局變量,必須加上global
聲明,但是對于自由變量,尚沒有類似的機制。所以,只能使用列表。(python3中引入了關鍵字:nonlocal
)
測試:
permutation('abcd')
運行結果:
['a', 'b', 'c', 'd']
['a', 'b', 'd', 'c']
['a', 'c', 'b', 'd']
['a', 'c', 'd', 'b']
['a', 'd', 'c', 'b']
['a', 'd', 'b', 'c']
['b', 'a', 'c', 'd']
['b', 'a', 'd', 'c']
['b', 'c', 'a', 'd']
['b', 'c', 'd', 'a']
['b', 'd', 'c', 'a']
['b', 'd', 'a', 'c']
['c', 'b', 'a', 'd']
['c', 'b', 'd', 'a']
['c', 'a', 'b', 'd']
['c', 'a', 'd', 'b']
['c', 'd', 'a', 'b']
['c', 'd', 'b', 'a']
['d', 'b', 'c', 'a']
['d', 'b', 'a', 'c']
['d', 'c', 'b', 'a']
['d', 'c', 'a', 'b']
['d', 'a', 'c', 'b']
['d', 'a', 'b', 'c']
共有24中全排列
step3 : 使用python標準庫
import itertoolst = list(itertools.permutations([1,2,3,4]))print(t)
運行結果:
[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]
新聞熱點
疑難解答