规格:Ubuntu 13.04,Python 3.3.1
背景:Python的初学者,遇到了这个“手动排序”的问题。
我被要求做的是:“让用户输入3个数值并将它们存储在3个不同的变量中。不使用列表或排序算法,手动将这3个数字从最小值排序到最大值。”
我能想到的是:
number = input("Please enter 3 numbers: ")
number = list(number)
a = int(number[0])
b = int(number[1])
c = int(number[2])
new_l = []
if a > b and a > c:
new_l.append(a)
if b > c:
new_l.append(b)
new_l.append(c)
else:
new_l.append(c)
new_l.append(b)
print(new_l)
if b > a and b > c:
new_l.append(b)
if a > c:
new_l.append(a)
new_l.append(c)
else:
new_l.append(c)
new_l.append(a)
print(new_l)
if c > a and c > b:
new_l.append(c)
if a > b:
new_l.append(a)
else:
new_l.append(b)
new_l.append(a)
print(new_l)
所以我的问题是: 我意识到我的解决方案非常有限。首先,它只能处理3个单个数字,因为一旦输入字符串被转换成一个列表,就无法将所有数字正确地分解成用户想要的单个数字。第二,通过使用这个解决方案,编码器被迫枚举3个数字相互比较的所有可能场景,这可能非常不灵活,如果说,脚本将被更改为接受用户输入的100多个数字。
如果你能分享一些关于上述问题的指导,或者关于如何以不同的方式解决这个问题,我会非常高兴!谢谢您。
对于三个项目,可以使用
max
和min
对它们进行排序:如果您不想使用排序算法,但可以使用列表,则可以每次弹出最小的项目并将其存储在新列表中:
虽然效率很低,但很管用。
使用气泡排序算法:
相关问题 更多 >
编程相关推荐