寻找第二个最小值和第二个最大值

时间:2019-08-13 15:47:40

标签: python

该程序用于查找第二个最小值和第二个最大值。算法中的错误是什么?它没有打印第二个最小值和第二个最大值。它仅打印最小和最大。

a = list(map(int, input().split()))

m1 = m2 = s1 = s2 = a[0]

for i in range(len(a)):
    if a[i] > m1:
        m1 = a[i]
    if a[i] > m2 and a[i] < m1:
        m2 = a[i]
    if a[i] < s1:
        s1 = a[i]
    if a[i] < s2 and s2 > s1:
        s2 = a[i]
    print(m2, s2)

1 个答案:

答案 0 :(得分:1)

使用this问答中的答案(获得here的奖励!),您可以

a = [12,7,5,3,8,5,2,3,42]
# assuming no duplicates in a and len(a) > 1:
if a[0] > a[1]: # make sure that m1 != m2 and s1 != s2
    m1, m2 = a[0], a[1]
    s1, s2 = a[0], a[1]
else:
    m1, m2 = a[1], a[0]
    s1, s2 = a[1], a[0]

for i in a:
    # maximum and second maximum
    if i > m1:
        m1, m2 = i, m1
    elif i > m2:
        m2 = i
    # minimum and second minimum
    if i < s1:
        s1, s2 = i, s1
    elif i < s2:
        s2 = i

print(m1, m2, s1, s2)
# 42 12 2 3

与有问题的代码相比

  • 正确初始化,以便逻辑起作用。将所有内容都设置为a[0]可能有效,例如如果a[0]不是最大值,则为最大值;如果a[0]是最小值不是,则最小值。两者都不是。
  • 修改逻辑,以便同时(而不是顺序)更新值。否则,条件将无法按照我的评论进行。

注意:我假设本练习的全部重点是有条件地完成所有操作。否则,您可以简化为

a = list(set([1,7,5,3,8,5,2,3,1])) # remove duplicates with set
m1, s1 = max(a), min(a)
_, _ = a.remove(m1), a.remove(s1)
m2, s2 = max(a), min(a)
print(m1, m2, s1, s2)
# 8 7 1 2

甚至是simpler

a_srt = sorted(list(set(a)))
m1, m2, s1, s2 = a_srt[-1], a_srt[-2], a_srt[0], a_srt[1]

...我敢打赌,还有更多的可能性。