Saturday, February 23, 2019

Nested Lists - Hacker Rank Solution

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.
Nested Lists  - Hacker Rank Solution
We can solve this challenge by using nested list.
Problem Setter's code:
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")
Problem Tester's code:
a = [[raw_input(), float(raw_input())] for i in xrange(int(raw_input()))]
s = sorted(set([x[1] for x in a]))
for name in sorted(x[0] for x in a if x[1] == s[1]):
    print name

4 comments:

  1. its showing list index out of range error

    ReplyDelete
  2. N = int(input())
    list = []
    num = []
    nl = []
    for i in range(0,N):
    a = input()
    b = float(input())
    num.append(b)
    list.append([a,b])
    #print(list)
    #print(num)
    num.sort()
    num.reverse()
    #print(num)
    c = num.count(min(num))
    number=num[len(num)-c-1]
    #print(number)
    for i in range(0,N):
    if(number==list[i][1]):
    #print(list[i][0])
    nl.append(list[i][0])
    nl.sort()
    #print(nl)
    for x in range(len(nl)):
    print (nl[x])

    ReplyDelete
  3. can u explain the problem setter code...
    which is mentioned above.

    ReplyDelete

Powered by Blogger.