У меня проблемы с пониманием этого кода - PullRequest
0 голосов
/ 07 июня 2019

Я новичок в python и пытаюсь учиться, тренируясь на hackerrank. Я не понимаю эту концепцию списка. Это проблема

Формат ввода:

Первая строка содержит целое число, количество студентов. Последующие строки описывают каждого студента через строки; первая строка содержит имя учащегося, а вторая строка содержит его оценку.

1010 * Ограничения *

Всегда будет один или несколько учеников, имеющих второй младший класс.

Формат вывода:

Напечатайте имя (имена) любого ученика, имеющего второй самый низкий класс по физике; если учеников несколько, упорядочите их имена в алфавитном порядке и напечатайте каждого в новой строке.

Пример ввода 0:

5

Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39

Пример вывода 0:

Berry

Harry

Код

from __future__ import print_function
score_list = {}
for _ in range(input()):
    name = raw_input()
    score = float(raw_input())
    if score in score_list:
        score_list[score].append(name)
    else:
        score_list[score] = [name]
new_list = []
for i in score_list:
     new_list.append([i, score_list[i]])
new_list.sort()
result = new_list[1][1]
result.sort()
print (*result, sep = "\n")

Я не могу понять функцию "in" здесь, не in проверяет значение в списке, и поэтому score_list не пусто?

Ответы [ 2 ]

1 голос
/ 07 июня 2019

Я добавил комментарии в коде для лучшего понимания, надеюсь, это поможет.

from __future__ import print_function
# Create an empty dict
score_list = {}
# Take a number input and run this loop that many times
for _ in range(input()):
    name = raw_input()
    score = float(raw_input())
    # if value of score is an existing key in dict, add name to the value of that key
    if score in score_list:
        score_list[score].append(name)
    else:
        # Else create a key with score value and initiate the value with a list
        score_list[score] = [name]
new_list = []
for i in score_list:
     new_list.append([i, score_list[i]])
new_list.sort()
result = new_list[1][1]
result.sort()
print (*result, sep = "\n")
0 голосов
/ 07 июня 2019

В первый раз словарь пуст, но во второй раз - нет. Я добавил комментарий к каждой строке.

# Import
from __future__ import print_function
# Create a new dictionary to save the scores
score_list = {}
# For every input, do something
for _ in range(input()):
    # Grab the name of the current user
    name = raw_input()
    # Grab the score of the current
    score = float(raw_input())
    # If the score is already in the list,
    # append the name to that score
    if score in score_list:
        score_list[score].append(name)
    # Else add the new score and name to the list
    else:
        score_list[score] = [name]
# Create a new list
new_list = []
# Copy score list into the new list
for i in score_list:
     new_list.append([i, score_list[i]])
# Sort on score value
new_list.sort()
# Return the second highest score
result = new_list[1][1]
# Sort the names of the result
result.sort()
# Print it
print (*result, sep = "\n")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...