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')