日期:2025/04/07 01:34来源:未知 人气:58
1、编程试题:
编写一个程序来找出给定数字的排列。
三位数的排列是指三个不同数字的所有可能的排列。例如,数字5,6和7的排列:
567
576
657
675
756
765
定义函数get_all_permutations(),该函数接受一个包含三个整数的列表作为参数。
在函数内部,找出所有可能的数字排列,并在新行中打印每个排列。
示例输入
1 2 3
示例输出
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
2、代码实现:
方法一:
可编辑代码如下:
#
#
#################### 方法一:嵌套的for循环
def get_all_permutations(digits):
for i in digits:
for j in digits:
for k in digits:
if i != j and j != k and i != k:
print(i, j, k, end="\n")
digits = list(map(int, input().split()))
get_all_permutations(digits)
方法二:
可编辑代码如下:
#
#
#################### 方法二:python函数permutations
from itertools import permutations
def get_all_permutations(digits):
for element in permutations(digits):
for j in element:
if element.index(j)+1 != len(element):
print(j,end=' ')
else:
print(j)
print(end="")
digits = list(map(int, input().split()))
get_all_permutations(digits)
3、代码分析:
本例采用了两种方法来实现,方法一采用for循环,方法二采用itertools例的排列组合函数
itertools.permutations 函数是Python标准库 itertools 模块中的一个函数,用于生成给定可迭代对象的所有排列组合
函数定义:itertools.permutations(iterable, r=None)
参数
iterable:必需,表示要进行排列组合的可迭代对象,例如:列表、字符串等。
r:可选,表示每个排列组合的长度。如果未提供该参数,则默认为可迭代对象的长度。
4、运行结果:
输入:
5 3 9
输出:
5 3 9
5 9 3
3 5 9
3 9 5
9 5 3
9 3 5