ブリブリ備忘録 おっ、python

HackerRankの問題とコメント(python3) 拙いですが...

Nested Lists 二重配列

・問題

Given the names and grades for each student in a Physics class of  students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.

Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line.

Input Format

The first line contains an integer, , the number of students. 
The  subsequent lines describe each student over  lines; the first line contains a student's name, and the second line contains their grade.

Constraints

  • There will always be one or more students having the second lowest grade.

Output Format

Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line.

Sample Input 0

5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39

Sample Output 0

Berry
Harry

Explanation 0

There are  students in this class whose names and grades are assembled to build the following list:

python students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]]

The lowest grade of  belongs to Tina. The second lowest grade of  belongs to both Harry and Berry, so we order their names alphabetically and print each name on a new line.

ソースコード

if __name__ == '__main__':
l1=[]
l2=[]
l3=[]
l4=[]
a=int(input())
for _ in range(a):
name = input()
score = float(input())
l1=[name,score]
l2.append(l1)
l3.append(score)
b=min(l3)
while min(l3)==b:
l3.remove(b) 
b=min(l3)
n=0
while n<a:
if l2 [n][1]==b:
l4.append(l2[n][0])
n+=1
l4.sort()
syuturyoku = '\n'.join(l4) 
print (syuturyoku)

・コメント

名前と点数が交互に並んだ入力から、点数が二番目に低い人の名前を抜き出し、出力する問題。また、複数人いる場合には名前をアルファベット順に並べる必要がある。

 

まず、名前と点数をコンマで挟んだ配列を作製し、その配列を空の配列に追加していくことで、二重配列を作っている。

さらにもう一つの配列を用意し、その中には点数のみを入れる。そして、前の問題でも行った、二番目に低い点数を見つける方法を用いて、その点数を得る

参考記事:↓二番目に低い点数を見つける方法

oltupython.hatenablog.com

そして二重配列の中からその点数の名前を見つけ出し、配列に追加する。そして、sortを用いて名前をアルファベット順に整理し、最終結果を出力する。

ただし、そのまま出力すれば、配列の形で出てきてしまうので、joinを用いてリスト内の文字を結合する。また、名前は改行して出力しなければならないので'\n'.join(l4) のように、joinの前に改行を意味する'\n'.が挿入されている。

・URL

https://www.hackerrank.com/challenges/nested-list/problem