Python 中的排列和組合?


在本節中,我們將學習如何使用 Python 程式語言查詢給定序列的排列和組合。

Python 相對於其他程式語言的一個關鍵優勢在於它自帶了大量的庫。

我們將使用 Python 內建的包來查詢給定序列的排列和組合。

查詢排列和組合的演算法

  • 步驟 1:匯入所需的包。第一步是匯入所需的包,因為我們將使用 itertools 包,所以我們只需使用以下命令匯入它。

>>> import itertools
>>>
  • 步驟 2:獲取序列的所有排列和組合。第二步是輸入一個序列/專案的列表作為輸入,該輸入將以元組列表的形式返回所有排列和組合。

  • 我們還可以設定排列和組合的長度。

  • 步驟 3:列印結果。最後一步是列印一組序列的所有排列和組合。我們可以使用迴圈函式來列印結果。

排列

讓我們找到一個包含三個專案的列表的排列。

示例 1

from itertools import permutations

seq = permutations(['a','b','c'])

for p in list(seq):
   print(p)

結果

('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')

示例 2

透過定義排列的長度來查詢排列。

from itertools import permutations

seq = permutations(['p', 'y', 't', 'h', 'o', 'n'], 2)

for p in list(seq):
   print(p)

結果

('p', 'y')
('p', 't')
('p', 'h')
('p', 'o')
('p', 'n')
('y', 'p')
('y', 't')
('y', 'h')
('y', 'o')
('y', 'n')
('t', 'p')
('t', 'y')
('t', 'h')
('t', 'o')
('t', 'n')
('h', 'p')
('h', 'y')
('h', 't')
('h', 'o')
('h', 'n')
('o', 'p')
('o', 'y')
('o', 't')
('o', 'h')
('o', 'n')
('n', 'p')
('n', 'y')
('n', 't')
('n', 'h')
('n', 'o')

組合

讓我們使用 Python 查詢序列的組合。

示例 1:確定組合的長度

#Import itertools package
from itertools import combinations

#Getting all combination of a particular length.
combi = combinations(['p', 'y', 't', 'h', 'o', 'n'], 5)

#Print the list of combinations

for c in list(combi):
   print(c)

結果

('p', 'y', 't', 'h', 'o')
('p', 'y', 't', 'h', 'n')
('p', 'y', 't', 'o', 'n')
('p', 'y', 'h', 'o', 'n')
('p', 't', 'h', 'o', 'n')
('y', 't', 'h', 'o', 'n')

示例 2:帶替換的組合

#Import itertools package
from itertools import combinations_with_replacement

#Getting all combination by defining a particular length.
combi = combinations_with_replacement(['p', 'y', 't', 'h', 'o', 'n'], 2)

#Print the list of combinations

for c in list(combi):
   print(c)

結果

('p', 'p')
('p', 'y')
('p', 't')
('p', 'h')
('p', 'o')
('p', 'n')
('y', 'y')
('y', 't')
('y', 'h')
('y', 'o')
('y', 'n')
('t', 't')
('t', 'h')
('t', 'o')
('t', 'n')
('h', 'h')
('h', 'o')
('h', 'n')
('o', 'o')
('o', 'n')
('n', 'n')

更新於: 2019年7月30日

1K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.