我为hackerrank编写了一些代码,但是它不适用于某些测试用例,这有什么问题呢?
该问题称为嵌套列表,这是链接:https://www.hackerrank.com/challenges/nested-list/problem?h_r=next-challenge&h_v=zen
if __name__ == '__main__':
students = []
for _ in range(int(input())):
name = input()
score = float(input())
students.append([name, score])
# making a set of all the scores
n = len(students)
score_list = []
for i in range(n):
score_list.append(students[i][1])
score_list.sort()
score_set = set(score_list)
required_score = list(score_set)[1]
# making a list of all the people with the required score
people = []
for i in range(n):
if students[i][1] == required_score :
people.append(students[i][0])
people.sort()
# printing each line
for i in range(len(people)):
print(people[i])
答案 0 :(得分:1)
首先,您可以使此代码更具“ pythonic”性。
if __name__ == '__main__':
students = []
for _ in range(int(input())):
name = input()
score = float(input())
students.append([name, score])
# making a set of all the scores
score_list = [student[1] for student in students]
这称为“列表理解”。与传统的“在for循环中添加”方法相比,创建列表要容易得多。
score_list.sort()
score_set = set(score_list)
required_score = list(score_set)[1]
我不太确定您在这里做什么。如果要从分数列表中进行设置,则无需排序。然后,将集转换回列表,并获取列表的第二项。我假设将集合转换为列表会以随机顺序为您提供列表。在python中实现它的方式可能并非如此,但是从语义上讲,将集转换为列表不会获得任何可靠的排序。
# making a list of all the people with the required score
people = []
for i in range(n):
if students[i][1] == required_score :
people.append(students[i][0])
我将在这里花一些时间在此for循环上。首先,python提供了一种遍历列表的简便方法。您无需按索引访问每个项目:
people = []
for student in students:
if student[1] == required_score :
people.append(student[0])
接下来,由于您的学生列表包含两个项目的列表,因此您可以在for循环中解压缩这些列表:
people = []
for name, score in students:
if score == required_score :
people.append(name)
同样,这可以通过转换为列表理解来完成,但是有些人可能更喜欢上面的版本,因为它更容易阅读:
people = [name for name, score in students if score == required_score]
# printing each line
for student in sorted(people):
print(student)
注意我在上一个循环中所做的更改。至于出了什么问题,我想这是您获取required_score编号的方式,但是却看不到输入和预期输出,这很难知道。