[英]I have to sort a stack in ascending order from top to bottom using only one queue
[英]I have to write a program to sort 5 input numbers in ascending order with using only "if" conditions
我被告知要编写一个程序来按升序对 5 个输入数字进行排序。 我已经完成了三个数字的基本解决方案,但我对如何处理 5 个数字感到困惑。 有什么帮助吗?
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
if a < b:
if b < c:
print (a, "<", b, "<", c)
else:
if a < c:
print (a, "<", c, "<", b)
else:
print (c, "<", a, "<", b)
else:
if c < b:
print (c, "<", b, "<", a)
else:
if c < a:
print (b, "<", c, "<", a)
else:
print (b, "<", a, "<", c)
满足您要求的最简单的解决方案是展开冒泡排序,它交换元素足够多次以保证最小元素在a
中,最大元素在e
中:
if b < a:
a, b = b, a
if c < b:
b, c = c, b
if d < c:
c, d = d, c
if e < d:
d, e = e, d
再复制并粘贴三次(因此,每次通过调整至少一个不在正确 position 中的元素到正确的 position 中;它的编写方式可以从每个后续通过中省略一些代码,但更容易复制并粘贴并做无意义的工作,而不是从每次通过中删除一个测试),然后以:
print(f'{a} <= {b} <= {c} <= {d} <= {e}')
这是一个非常丑陋的解决方案(你不应该在现实生活中复制和粘贴这样的代码),但如果你对你被允许做的事情有超级限制,它就可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.