【问题标题】:how to sort multiple arguments without using the sort function in python?如何在不使用python中的排序函数的情况下对多个参数进行排序?
【发布时间】:2021-12-12 05:14:21
【问题描述】:

我的目标是将三个数字排序为 a、b 和 c,其中 a 是最大的,b 是中间的,c 是最小的。为此,我需要编写一个函数。但是,我尝试了多种方法,但没有找到让它工作的方法。

num1 = int(input("input an integer: "))
num2 = int(input("input another integer: "))
num3 = int(input("input another integer: "))

def simple_sort(a,b,c):
    if a > b and a > c:
        return a
    if b < a and b > c:
        return b
    if c < a and c < b:
        return c

a,b,c=simple_sort(num1,num2,num3)
print(a,b,c)

#for it to be correct, when i do print(a,b,c), it should print num1, num2 and num3
#in ascending order

【问题讨论】:

  • 一旦满足一个条件,您将返回该值。此外,您没有所有可能的结果。 . .如果我输入1,2,3 会怎样?不满足任何条件,不会返回任何内容。
  • return sorted([a,b,c], reverse=True)
  • @sahasrara62 OP 在标题“不使用排序功能”中声明——大概包括.sortsorted
  • 也许然后写一个排序算法
  • geeksforgeeks.org/python-program-for-insertion-sort 一个可以实现的简单插入排序

标签: python python-3.x sorting


【解决方案1】:

您只返回一个值(abc),您需要返回 tuplelist

def simple_sort(a,b,c):
    if a < b:
        a,b = b,a
    # above guarantees that a > b

    if c > a:
        return (c,a,b)
    elif c > b:
        return (a,c,b)
    else:
        return (a,b,c)

values = list(map(int,input("Input three integers separated by spaces: ").split()))
print(simple_sort(*values))

【讨论】:

  • 您可以通过确保a &gt; b 来简化此操作,必要时进行交换。那么你只需要检查三种情况,具体取决于c 是最大值、中间值还是最小值。
  • 最好写个排序算法
  • @chepner 非常感谢,第一个对我有用,虽然我不得不翻转 因为它应该是按升序排列的。
  • @sahasrara62 这一种排序算法,如果你事先知道只有三个数字需要排序。
  • @chepner 仅适用于这种情况
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-17
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 2023-03-19
  • 2016-07-07
  • 1970-01-01
相关资源
最近更新 更多