Finding the second largest element in a list (for duplicate elements)(查找列表中的第二大元素(对于重复元素))
本文介绍了查找列表中的第二大元素(对于重复元素)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试查找数组中的第二大元素。我的代码对大多数输入都有效,但对于某些输入,它却失败了。
另外,如果我输入[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)
请谁来解释一下背后的逻辑。
推荐答案
问题在于您在此处编写的第一个和第二个最大值的初始化
if arr[0] >= arr[1]:
first_max = arr[0]
second_max = arr[1]
else:
first_max = arr[1]
second_max = arr[0]
在[6,6,6,6,6,6,6,6,6,5]的情况下,first_max和Second_max都等于6,并且在被指定为5时无法更改,因为第二个max仍然大于5。
解决方案是编辑这部分代码
之前
elif arr[i] > second_max and arr[i] != first_max:
second_max = arr[i]
之后
elif first_max == second_max or (arr[i] > second_max and arr[i] != first_max:
second_max = arr[i])
这篇关于查找列表中的第二大元素(对于重复元素)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:查找列表中的第二大元素(对于重复元素)
基础教程推荐
猜你喜欢
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
