网站首页 > 基础教程 正文
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、代码实现:
方法一:
#!/usr/bin/python3.9
# -*- coding: utf-8 -*-
#
# Copyright (C) 2024 , Inc. All Rights Reserved
#
# @Time : 2024/2/6 19:46
# @Author : fangel
# @FileName : 97. 三位数的排列.py
# @Software : PyCharm
#################### 方法一:嵌套的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)
方法二:
#!/usr/bin/python3.9
# -*- coding: utf-8 -*-
#
# Copyright (C) 2024 , Inc. All Rights Reserved
#
# @Time : 2024/2/6 19:46
# @Author : fangel
# @FileName : 97. 三位数的排列.py
# @Software : PyCharm
#################### 方法二: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
猜你喜欢
- 2024-10-31 Python办公神器:教你如何快速分拆、删页、合并PDF文件
- 2024-10-31 Python3中的字符串操作 python3 字符串操作
- 2024-10-31 学好了Python,我们就可以玩转字符串算法了
- 2024-10-31 玩转Python—字符串使用教程 python字符串常用方法
- 2024-10-31 你会在 Python 中使用字符串吗? python字符串怎么用
- 2024-10-31 Python3中可能不会用到的10个功能!但是能让你的代码更简洁直观
- 2024-10-31 python作业(三) python编程作业
- 2024-10-31 手把手教你写爬虫 |Python 采集大众点评数据采集实战
- 2024-10-31 「python杂谈」使用多个分隔符分隔字符串
- 2024-10-31 如何用Python+OpenCV处理图像色彩?终于有人讲明白了
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- 单例 (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)