您好,登錄后才能下訂單哦!
這篇文章給大家介紹Python中怎么實現全排列操作,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
step 1: 列表的全排列:
這個版本比較low
# -*-coding:utf-8 -*- #!python3 def 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 -*- #!python3 def 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 itertools t = 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)]
可以指定排列的位數:
import itertools t = itertools.permutations([1,2,3,4],3) #只排列3位 print(list(t))
運行結果:
[(1, 2, 3), (1, 2, 4), (1, 3, 2), (1, 3, 4), (1, 4, 2), (1, 4, 3), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 1, 2), (3, 1, 4), (3, 2, 1), (3, 2, 4), (3, 4, 1), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2)]
關于Python中怎么實現全排列操作就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。