Nested lists in python - HackerRank solution
Solution for hackerRank problem Nested lists in python
Problem :
Given the names and grades for each student in a 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 second lowest grade, order their names alphabetically and print each name on a new line.
Example
records=[ ["chi", 20.0], ["beta", 50.0], ["alpha", 50.0]
The ordered list of scores is [20.0, 50.0], so the second lowest score is 50.0 . There are two students with that score: ["beta", "alpha"] . Ordered alphabetically, the names are printed as:
alphabeta
Input Format
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 belongs toTina. 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.
Procedure :
1. Start
2. Get the number of students (n) as input from the user.
3. Loop from 0 to n
Get the student name and mark as input from the user.
Store the input in a dictionary as key-value pairs.
4. Store the scores of students (i.e. values of the dictionary) in a list.
5. Sort the list.
6. Remove the duplicate values in the list.
7. Second lowest mark is equal to the element at index 1 in the sorted list.
8. Print the corresponding name of the student.
9. End
Code :
#Getting the number of students from user
no_of_stu=int(input())
#Creating an empty dictionary
marksheet={}
#Storing the name as keys and its corresponding mark as values in the dictionary
for i in range(no_of_stu):
name=str(input())
mark=input()
marksheet[name]=float(mark)
#Storing the marks in a list
score=list(marksheet.values())
#Sorting the list
score.sort()
#Removing duplicate elements in the list
unique_score=[]
for elt in score:
if elt not in unique_score:
unique_score.append(elt)
#Finding the second lowest mark
second_low=unique_score[1]
stu_name=[]
for names,marks in marksheet.items():
if(marks==second_low):
stu_name+=[names]
stu_name.sort()
for stu in stu_name:
print(stu)
Explanation of the python functions used :
- values()- returns all the values in the dictionary.
- items()- returns all the keys and values in the dictionary as key value pair.
- append()- inserts the element at last of the list.
- sort()- sorts the list.
Comments
Post a Comment