专业编程基础技术教程

网站首页 > 基础教程 正文

Python第97题:三位数的排列【PythonTip题库300题】

ccvgpt 2024-10-31 12:39:06 基础教程 6 ℃

1、编程试题:

编写一个程序来找出给定数字的排列。

Python第97题:三位数的排列【PythonTip题库300题】

三位数的排列是指三个不同数字的所有可能的排列。例如,数字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

Tags:

最近发表
标签列表