HackerRank Solution: Python Nested Lists [4 Methods]


Written by - Bashir Alam
Reviewed by - Deepak Prasad

Question: Python Nested Lists [Basic Data Types]

Given the names and grades for each student in a class of Nstudents, 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 second lowest grade, order their names alphabetically and print each name on a new line.

Input Format:

The first line contains an integer, N, the number of students.
The 2Nsubsequent lines describe each student over lines.

  • The first line contains a student’s name.
  •  The second line contains their grade.

Constraints:

  • 2≤N≤5
  • 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. 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 37.21 belongs to Tina. The second lowest grade of 37.21 belongs to both Harry and Berry, so we order their names alphabetically and print each name on a new line.

 

Possible solutions

Now let us solve the problem using various possible solutions. The following code is already given in the Hacer Rank:

if __name__ == '__main__':
    for _ in range(int(input())):
        name = input()
        score = float(input())

Let us move toward the solutions:

 

Solution-1: Using list comprehension

Let us first solve the problem using list comprehension:

if __name__ == '__main__':
    scores = []
    for _ in range(int(input())):
        name = input()
        score = float(input()) 
        scores.append([name, score])
    
    # Find min score
    min_score = min(scores, key = lambda x: x[1])
    
    # Keep only students with score higher than min
    scores = [score for score in scores if score[1] > min_score[1]]
    
    # Find second min score
    second_min_score = min(scores, key = lambda x: x[1])
    
    # Keep only students with second min score
    scores = [score for score in scores if score[1] == second_min_score[1]]
    
    # Sort students alphabetically
    scores.sort(key = lambda x: x[0])
    
    for score in scores:
        print(score[0])

This code takes in a number of student names and scores, then stores them in a list of lists where each sublist contains a name and a score. It then finds the minimum score, removes all students with a score lower than the minimum from the list, finds the new minimum score, removes all students with a score lower than the second minimum, and sorts the remaining students alphabetically by name. Finally, it prints the names of the remaining students in alphabetical order.

 

Solution-2: Using for loops

We can also use for loop to solve the problem as shown below:

if __name__ == '__main__':
    num = []
    arr = []
    for _ in range(int(input())):
        name = input()
        score = float(input())
        arr.append([name, score])
        num.append(score)
        
    num.sort()
    second_min = 0
    mini = num[0]
    arr.sort()
    for i in num:
        if i != mini:
            second_min = i
            break
    
    for i in arr:
        if i[1] == second_min:

            print(i[0])
        

his code takes in a number of student names and scores, then stores them in a list called "arr" where each sublist contains a name and a score, and in another list "num" where each element is the score. It then sorts the list "num" and assigns the first element to a variable "mini" and assigns the second smallest element to a variable "second_min". Then, it sorts the "arr" list and iterates through it and if it finds a match with the "second_min" value it prints the corresponding name. This code finds the second-lowest score and prints the names of students who scored that score.

 

Solution-3: Using try-except block

Let us modify the above code a little bit and use try-except block to solve the problem:

if __name__ == '__main__':
    grade_book=dict()
    grades=set()
    for _ in range(int(input())):
        name = input()
        score = float(input())
        grade_book[name]=score
        grades.add(score)
    grades=list(grades)
    grades=sorted(grades)
    people=[]
    for i in range(len(grade_book)):
        try:
            people.append(list(grade_book.keys())
            [list(grade_book.values()).index(grades[1])])
            grade_book.pop(list(grade_book.keys())
            [list(grade_book.values()).index(grades[1])])
        except:
            break
    people=sorted(people)
    for i in people:
        print(i)

This code creates an empty dictionary called "grade_book" to store student names and scores, and an empty set called "grades" to store the unique scores. It then takes input of a number of student names and scores and adds them to the "grade_book" dictionary and "grades" set. It then converts "grades" set to a list, sorts it, and initializes an empty list called "people". It then iterates through the "grade_book" dictionary and finds the second lowest score, gets the names of students who scored that grade, adds it to the "people" list and removes that student from the "grade_book" dictionary. Finally it sorts "people" alphabetically and prints the names of students who scored the second lowest grade.

 

Solution-4: Using the sorted method

We can use the sorted method to solve the problem:

if __name__ == '__main__':
    li = []
    for _ in range(int(input())):
        name = input()
        score = float(input())
        li.append([name,score])
scr = [x[1] for x in li]
min_li = sorted(set(scr))
stud = sorted([y[0] for y in li if y[1]==min_li[1]])
[print(k) for k in stud]

This code takes in a number of student names and scores and stores them in a list of lists called "li" where each sublist contains a name and a score. Then it creates a new list called "scr" containing only the scores from "li" and assigns it to variable "scr". It then creates a new variable "min_li" that stores a set of scores sorted in ascending order. Next, it creates a new variable "stud" which contains the names of students whose scores match the second-lowest score from "min_li". Finally, it iterates through "stud" and prints the names of students who scored the second lowest grade.

This code is different from previous ones in that it used list comprehension to get the scores and student names separately and it uses the built-in function "sorted" to sort "min_li" and "stud" and also it uses one-line comprehension to print the names of students.

 

Summary

In this short article, we discussed how we can solve the Nested Lists problem using various methods. We covered four different methods to solve the problem and explained each of the solutions.

 

Further Reading

Question on Hacker Rank: Python Nested Lists [Basic Data Types]

 

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and predictive models. You can reach out to him on his Linkedin or check his projects on GitHub page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment