lis中的第二最小元素

2024-09-30 18:30:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我得找出成绩倒数第二的学生的名字。我的代码在某些测试用例中运行良好,但这一个特别让我感到困扰:

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公司我用过的方法,但我不知道它是什么。在


Tags: inforinputnamesrangetempintheapq
3条回答

你错了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,您可以使用此代码来获得相同的答案。在

# 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 = list(set([x[1] for x in builtlist]))
secondsmall = sorted(temp)[1]

for j in range(len(builtlist)):
    if (builtlist[j][1]==secondsmall):
        names.append(builtlist[j][0])
list_print = sorted(names)
print(*list_print, sep = "\n")

这里发生了很多事情。在

首先,stackoverflow不存在来调试代码,这是对网站的滥用。以后请不要这样做,并注意

code tags.

其次,heapq.nsmallest公司()将返回请求的最小元素数。如果两个元素最小并且共享一个值,那么它们都将被返回。因此,代码按预期运行。在

我会研究python字典和hashset来解决这个问题。还有一个更优雅的解决方案。在

不需要使用heapq

def second_smallest(builtlist):
    # sort on key.
    temp = sorted(builtlist, key = lambda x: x[1])
    second_smallest_group = []
    current_val = 0
    # iterate list comparing i with i + 1
    for i in range(len(temp) - 1):
        current_val = temp[i][1]
        # if in set of first smallest ignore.
        if current_val == temp[i+1][1] and len(second_smallest_group) == 0:
            continue
        # if in second set of smallest add.
        elif current_val == temp[i+1][1] and len(second_smallest_group) > 0: 
            second_smallest_group.append(temp[i+1][0])
        # if changing between sets add first member.
        elif len(second_smallest_group) == 0:
            second_smallest_group.append(temp[i+1][0])
        # if we move to another group break.
        else:
            break
    return second_smallest_group



builtlist = [["Rachel", -50], ["Mawer", -50], ["Sheen", -50],["Shaheen",51]]

print(second_smallest(builtlist))

builtlist = [["Shadab",8], ["Varun", 8.9], ["Sarvesh", 9.5], ["Harsh",10]]

print(second_smallest(builtlist))

相关问题 更多 >