我有一些我参加的初学者类(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))))
当我尝试运行命令时,它会给出最低值和最高值。我怎样才能解决这个问题。谢谢。
最佳答案
要仅使用 min
和 max
对少量项目进行排序,您可以使用 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/