如何仅用条件排序四个数字(不使用数组)
我在学习Python的入门课程时遇到了一些问题。我们的任务是将四个整数按从大到小的顺序排列,然后程序还要显示你输入这些数字的顺序。
举个例子: 输入:5, 10, 3, 3 输出:(1) 第二个输入 (2) 第一个输入 (3) 第三个和第四个输入
唯一的问题是我们不能使用数组或内置的排序函数,只能用条件语句。
我们在课堂上已经完成了代码的一部分。这里有一个我们做的排序算法的示例:
# 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
...等等。
我不太确定接下来该怎么做。问题是,上面的代码在排序时会忘记原始输入的顺序,因为你给新值赋值了。你们觉得我缺少了什么吗?
4 个回答
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)
2
这里提到的“少一次比较”是指在进行排序时,有一种方法可以减少比较的次数。这种方法被称为“针对固定条件交换的最佳排序网络”。简单来说,就是在特定情况下,按照一定的规则交换元素,可以让排序变得更高效。
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
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
这是一种你可以尝试的方法...
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