【发布时间】:2019-04-14 15:04:24
【问题描述】:
我正在尝试查找数组中的第二大元素。我的代码适用于大多数输入,但对于某些输入,它失败了。
另外,如果我输入[6, 6, 6, 5],程序应该输出5作为第二大而不是6。
对于[6,6,6,6,6,6,6,6,6,5],它打印的是 6 而不是 5。
对于重复元素,它会给出错误的结果。
# Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score.
# You are given scores. Store them in a list and find the score of the runner-up.
if __name__ == '__main__':
n = int(input("Enter the total numbers: "))
arr = list(map(int, input("Enter the numbers: ").split()))
if arr[0] >= arr[1]:
first_max = arr[0]
second_max = arr[1]
else:
first_max = arr[1]
second_max = arr[0]
for i in range(2, n):
if arr[i] > first_max:
second_max = first_max
first_max = arr[i]
elif arr[i] > second_max and arr[i] != first_max:
second_max = arr[i]
print(second_max)
请有人解释一下它背后的逻辑。
【问题讨论】:
-
为什么不
sorted(set(arr))[-2]? -
那行得通。但我想知道一般逻辑,而不是特定语言的解决方案。
-
我主要是要求重复元素。
-
在源代码中包含一个问题陈述——下一次,使用docstring。如果你为业务逻辑定义了一个函数,你也可以在那里添加一个。