python - 如何使用 min 和 max 函数按降序对值进行排序

标签 python python-3.x

我有一些我参加的初学者类(class)的作业。我需要帮助对多个值进行排序。我使用输入函数输入 4 个随机数,然后我必须使用 min() 和 max() 函数按从低到高的顺序对 4 个数字进行排序。这是我目前所拥有的

first_integer = input("Please enter the first integer: ")
second_integer = input("Please enter the second integer: ")
third_integer = input("Please enter the third integer: ")
fourth_integer = input("Please enter the fourth integer: ")

integers = (first_integer, second_integer, third_integer, fourth_integer)

print ("The integers in increasing order are", sorted((min (integers)) + (max(integers))))

当我尝试运行命令时,它会给出最低值和最高值。我怎样才能解决这个问题。谢谢。

最佳答案

要仅使用 minmax 对少量项目进行排序,您可以使用 sorting network .这是该维基百科文章介绍部分末尾的 4 个项目的示例排序网络的实现。我的代码通过对输入列表的所有 24 个排列进行排序来验证它是否有效。

from itertools import permutations

def sort2(a, b):
    return min(a, b), max(a, b)

def sort4(a, b, c, d):
    a, c = sort2(a, c)
    b, d = sort2(b, d)
    a, b = sort2(a, b)
    c, d = sort2(c, d)
    b, c = sort2(b, c)
    return a, b, c, d

# Test all permutations
for seq in permutations([1, 2, 3, 4]):
    print(seq, sort4(*seq))

输出

(1, 2, 3, 4) (1, 2, 3, 4)
(1, 2, 4, 3) (1, 2, 3, 4)
(1, 3, 2, 4) (1, 2, 3, 4)
(1, 3, 4, 2) (1, 2, 3, 4)
(1, 4, 2, 3) (1, 2, 3, 4)
(1, 4, 3, 2) (1, 2, 3, 4)
(2, 1, 3, 4) (1, 2, 3, 4)
(2, 1, 4, 3) (1, 2, 3, 4)
(2, 3, 1, 4) (1, 2, 3, 4)
(2, 3, 4, 1) (1, 2, 3, 4)
(2, 4, 1, 3) (1, 2, 3, 4)
(2, 4, 3, 1) (1, 2, 3, 4)
(3, 1, 2, 4) (1, 2, 3, 4)
(3, 1, 4, 2) (1, 2, 3, 4)
(3, 2, 1, 4) (1, 2, 3, 4)
(3, 2, 4, 1) (1, 2, 3, 4)
(3, 4, 1, 2) (1, 2, 3, 4)
(3, 4, 2, 1) (1, 2, 3, 4)
(4, 1, 2, 3) (1, 2, 3, 4)
(4, 1, 3, 2) (1, 2, 3, 4)
(4, 2, 1, 3) (1, 2, 3, 4)
(4, 2, 3, 1) (1, 2, 3, 4)
(4, 3, 1, 2) (1, 2, 3, 4)
(4, 3, 2, 1) (1, 2, 3, 4)

正如维基百科提到的,对于少量项目,排序网络比其他排序算法更有效。但是,我的代码将比使用 Python 的内置 .sort 方法或 sorted 函数慢,因为它们以 C 速度运行。

关于python - 如何使用 min 和 max 函数按降序对值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35954098/

相关文章:

javascript - django 形成一个弹出对话框

python - BeautifulSoup 选择 sibling 不工作

python - jupyter 笔记本 vs jupyter 控制台 : display of markdown (and latex, html 等)对象

python - 保留 XML 属性顺序?

python - 大多数 pythonic3 dezip(?) 实现

string - 用C API提取python str,兼容python 2&3

c++ - 使用共享内存在 C++ 和 Python 之间进行快速通信

python - 如何将 pip install 转换为 Poetry 文件?

Python Config Parser 环境变量

Python - 打印直到标记(a la PHP)?