我得找出成绩倒数第二的学生的名字。我的代码在某些测试用例中运行良好,但这一个特别让我感到困扰:
4 Rachel -50 Mawer -50 Sheen -50 Shaheen 51
返回的输出为
Mawer Rachel Sheen
沙欣的成绩排在第二位,应该是最优秀的。我不知道我哪里出错了。此外,我在分数作为浮动输入时遇到问题:
4 Shadab 8 Varun 8.9 Sarvesh 9.5 Harsh 10
抛出的输出是Sarvesh,而它应该是Varun。在
import heapq
# range(int(input())):
n = int(input())
builtlist = []
temp= []
names = []
for i in range(0, n):
name = input()
score = float(input())
builtlist.append([name, score])
temp = sorted(builtlist, key = lambda x: x[1])
#minvalue = min(temp, key= lambda x: x[1])
for j in range(len(temp)):
secondsmall = heapq.nsmallest(2, temp)[-1]
if (temp[j][1]==secondsmall[1]):
names.append(temp[j][0])
list = sorted(names)
print(*list, sep = "\n")
我想这有点麻烦heapq.nsmallest公司我用过的方法,但我不知道它是什么。在
你错了
temp = sorted(builtlist, key = lambda x: x[1])
,heapq.nsmallest(2,temp)
返回temp中最小的n个元素,在您的例子中它将是[50,50,50,51]
,因此它将返回[50, 50]
使用temp = list(set(temp))
你的代码就可以工作了。在如果您不想使用heapq,您可以使用此代码来获得相同的答案。在
这里发生了很多事情。在
首先,stackoverflow不存在来调试代码,这是对网站的滥用。以后请不要这样做,并注意
其次,heapq.nsmallest公司()将返回请求的最小元素数。如果两个元素最小并且共享一个值,那么它们都将被返回。因此,代码按预期运行。在
我会研究python字典和hashset来解决这个问题。还有一个更优雅的解决方案。在
不需要使用
heapq
:相关问题 更多 >
编程相关推荐