我的Python入门课程遇到了一些麻烦。我们的任务是按降序对四个整数输入进行排序,然后程序也应该指出你在输入中键入的顺序。
例如: 输入:5,10,3,3 输出:(1)第二输入(2)第一输入(3)第3,第4输入
唯一的问题是我们不应该使用数组或内置排序函数,而只能使用条件。
我们已经在课堂上完成了上半部分代码。以下是我们所做的排序算法示例:
# user enters a, b, c, d
if a > b:
two = a
one = b
if c > d:
four = c
three = d
if two > four:
handle = three
three = four
four = two
two = handle
......等等。
我不确定如何从那里开始。问题是,由于您分配了新值,因此上面的代码会忘记原始输入的顺序。关于我在这里缺少什么的想法?
答案 0 :(得分:6)
您可以实施硬编码冒泡排序
if a > b: b, a = a, b
if b > c: c, b = b, c
if c > d: d, c = c, d
if a > b: b, a = a, b
if b > c: c, b = b, c
if a > b: b, a = a, b
答案 1 :(得分:2)
one,two,three,four = [random.random() for _ in range(4)]
changed = 1
while changed:
changed = 0
if one > two:
one,two = two,one
changed = 1
if two > three:
two,three = three,two
changed = 1
if three > four:
three,four = four,three
changed = 1
是你可以做到的一种方式......
答案 2 :(得分:1)
少一点比较:
if a > b: a, b = b, a
if c > d: c, d = d, c
if a > c: a, c = c, a
if b > d: b, d = d, b
if b > c: b, c = c, b
答案 3 :(得分:0)
如果你有足够的时间也可以尝试蛮力,
def mymax(a, b, c):
if a > b:
if a > c:
return a
else:
return c
else:
if b > c:
return b
else:
return c
def sort(p, q, r, s):
maximum = mymax(p, q, r)
if maximum > s:
first_max = maximum
if first_max == p:
maximum = mymax(q, r, s)
second_max = maximum
if second_max == q:
if r > s:
return first_max, second_max, r, s
else:
return first_max, second_max, s, r
elif second_max == r:
if q > s:
return first_max, second_max, q, s
else:
return first_max, second_max, s, q
elif second_max == s:
if q > r:
return first_max, second_max, q, r
else:
return first_max, second_max, r, q
elif first_max == q:
maximum = mymax(p, r, s)
second_max = maximum
if second_max == p:
if r > s:
return first_max, second_max, r, s
else:
return first_max, second_max, s, r
elif second_max == r:
if p > s:
return first_max, second_max, p, s
else:
return first_max, second_max, s, p
elif second_max == s:
if p > r:
return first_max, second_max, p, r
else:
return first_max, second_max, r, p
elif first_max == r:
maximum = mymax(p, q, s)
second_max = maximum
if second_max == p:
if q > s:
return first_max, second_max, q, s
else:
return first_max, second_max, s, q
elif second_max == q:
if p > s:
return first_max, second_max, p, s
else:
return first_max, second_max, s, p
elif second_max == s:
if p > q:
return first_max, second_max, p, q
else:
return first_max, second_max, q, p
else:
first_max = s
second_max = maximum
if second_max == p:
if q > r:
return first_max, second_max, q, r
else:
return first_max, second_max, r, q
elif second_max == q:
if p > r:
return first_max, second_max, p, r
else:
return first_max, second_max, r, p
elif second_max == r:
if p > q:
return first_max, second_max, p, q
else:
return first_max, second_max, q, p
print sort(1, 2, 3, 4)
print sort(4, 3, 2, 1)