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')
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP