We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
1.[marks for name, marks in marksheet]
It is the list comprehension method for creating a list here we create a list in the same order of marks as the user entered by simultaneously running the score and marks in the for loop.
2.set([marks for name, marks in marksheet])
It creates a set of the given values in the list this is done to avoid the repeated values in case any.
3.list(set([marks for name, marks in marksheet]))
Now again we create a list to allow us to sort the elements in order using the sorted fucntions we can't sort sets as there is no proper order of arrangement in sets.
so we use sorted to sort the list and then we pick the second element from first(index 1) and store it in the second_highest variable which gives us the second lowest mark(Yeah you read it right ) in the list.
Now for the second line we do,
[a for a,b in sorted(marksheet) if b == second_highest]
we do list comprehension with a condtion to create a list of the names which have the second_highest as their marks.
we use sorted marksheet as we have to print the name in ascendin order.
join() function is used to join the list into a string we put '\n' in the '.' before join to make sure print the names in linewise format as prescribed by the question.
Hope it was clear:)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Nested Lists
You are viewing a single comment's thread. Return to all comments →
1.[marks for name, marks in marksheet] It is the list comprehension method for creating a list here we create a list in the same order of marks as the user entered by simultaneously running the score and marks in the for loop.
2.set([marks for name, marks in marksheet]) It creates a set of the given values in the list this is done to avoid the repeated values in case any.
3.list(set([marks for name, marks in marksheet])) Now again we create a list to allow us to sort the elements in order using the sorted fucntions we can't sort sets as there is no proper order of arrangement in sets. so we use sorted to sort the list and then we pick the second element from first(index 1) and store it in the second_highest variable which gives us the second lowest mark(Yeah you read it right ) in the list.
Now for the second line we do,
[a for a,b in sorted(marksheet) if b == second_highest] we do list comprehension with a condtion to create a list of the names which have the second_highest as their marks. we use sorted marksheet as we have to print the name in ascendin order.
join() function is used to join the list into a string we put '\n' in the '.' before join to make sure print the names in linewise format as prescribed by the question.
Hope it was clear:)