Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to display all second lowest grade student name from nested list
Suppose we have the names and grades for each student in a nested list, we have to display the names of any students having the second lowest grade. If there are more than one students with the second lowest grade, reorder these in alphabetical order and print each name on a new line.
So, if the input is like students = [['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]], then the output will be Amal and Bimal, both having the second lowest score of 37, displayed in alphabetical order.
Algorithm Steps
To solve this, we will follow these steps ?
- Find the minimum grade among all students
- Filter out students with the minimum grade
- Find the minimum grade from the remaining students (second lowest overall)
- Extract and sort student names with the second lowest grade alphabetically
- Display each name on a new line
Example
Let us see the following implementation to get better understanding ?
def solve(students):
min_mark = min(x[1] for x in students)
students = [x for x in students if x[1] > min_mark]
min2_mark = min(x[1] for x in students)
students = sorted([x[0] for x in students if x[1] == min2_mark])
for x in students:
print(x)
students = [['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]]
solve(students)
Amal Bimal
How It Works
Let's trace through the algorithm with our example data:
- Initial data: [['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]]
- Find minimum grade: min_mark = 36 (Tarun's grade)
- Filter out minimum: [['Amal',37],['Bimal',37],['Akash',41],['Himadri',39]]
- Find second lowest: min2_mark = 37
- Extract and sort names: ['Amal', 'Bimal'] (already in alphabetical order)
Alternative Implementation
Here's a more concise version using set operations ?
def find_second_lowest(students):
grades = sorted(set(x[1] for x in students))
second_lowest = grades[1]
names = [x[0] for x in students if x[1] == second_lowest]
return sorted(names)
students = [['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]]
result = find_second_lowest(students)
for name in result:
print(name)
Amal Bimal
Conclusion
This program efficiently finds students with the second lowest grade by first identifying the minimum grade, filtering it out, then finding the next minimum. The names are sorted alphabetically before display, ensuring consistent output order.
