Python教程-Python中的排列与组合

在本教程中,我们将学习如何使用Python获取给定数据的排列和组合。我们将使用Python内置的包来找到给定数字的排列和组合。
排列和组合是数学中的重要部分。Python提供了itertools库,其中包含用于计算排列和组合的内置函数。
导入所需的库
要计算排列和组合,我们需要导入itertools库。我们可以使用以下命令导入它。
import itertools
上述语句将导入itertools库并形成其函数的路径。
现在,我们需要创建一个作为输入的序列列表。这个输入列表将返回一个包含排列和组合的元组。我们还可以设置排列和组合的长度。
排列
排列是一组元素的排列,其中顺序很重要。Python itertools模块提供内置的permutation()方法来查找排列。让我们了解以下示例。
示例 -
from itertools import permutations
seq = permutations(['1','2','3'])
print(seq)
for p in list(seq):
print(p)
输出:
('1', '2', '3')
('1', '3', '2')
('2', '1', '3')
('2', '3', '1')
('3', '1', '2')
('3', '2', '1')
在上面的代码中,我们导入了itertools模块。我们调用了permutation()方法,它接受字符串作为参数并提供一个itertools对象。必须使用for循环来获取每个排列。
让我们取两组排列。
示例 - 2
from itertools import permutations
seq = permutations(['A','B'])
for p in list(seq):
print(p)
输出:
('A', 'B')
('A', 'C')
('B', 'C')
示例 - 3
from itertools import permutations
list1 = [1, 2, 3, 4]
seq = permutations(list1)
print(seq)
for p in list(seq):
print(p)
输出:
(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)
在上面的代码中,我们得到了多个整数的组合。
固定长度的排列
我们可以计算固定长度集合的排列,其中我们只取每个元素排列的指定数量。让我们了解以下示例。
示例 -
from itertools import permutations
seq = permutations(['H', 'e', 'l', 'l', 'o'], 3)
for p in list(seq):
print(p)
输出:
('H', 'e')
('H', 'l')
('H', 'l')
('H', 'o')
('e', 'H')
('e', 'l')
('e', 'l')
('e', 'o')
('l', 'H')
('l', 'e')
('l', 'l')
('l', 'o')
('l', 'H')
('l', 'e')
('l', 'l')
('l', 'o')
('o', 'H')
('o', 'e')
('o', 'l')
('o', 'l')
在上面的代码中,我们通过传递长度为两个的方式计算了固定排列。
字符串的组合
组合是一个元素的集合,其中顺序无关紧要。Python的itertools模块提供了combination()方法来计算给定数据的组合。我们可以计算字符串的组合。让我们了解以下示例。
示例 -
import itertools
seq = "ABC"
com_seq = itertools.combinations(seq, 2)
for c in com_seq:
print(c)
输出:
('A', 'B')
('A', 'C')
('B', 'C')
具有替换的组合
itertools模块包含另一个称为combination_with_replacement()的方法,该方法考虑了数字本身的组合。让我们了解其示例。
数字集的组合
import itertools
v = [1, 2, 3, 4]
com_seq = itertools.combinations_with_replacement(v, 3)
for i in com_seq:
print(i)
输出:
(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 1, 4)
(1, 2, 2)
(1, 2, 3)
(1, 2, 4)
(1, 3, 3)
(1, 3, 4)
(1, 4, 4)
(2, 2, 2)
(2, 2, 3)
(2, 2, 4)
(2, 3, 3)
(2, 3, 4)
(2, 4, 4)
(3, 3, 3)
(3, 3, 4)
(3, 4, 4)
(4, 4, 4)
在这个教程中,我们已经讨论了使用Python脚本找到给定数据的排列和组合的itertools模块。