'How to find a name with the fourth highest score?

pardon this silly question but I need your help.

I have a list of name, let's say

name = ['Alpha','Betta','Chroma','Delta','Echo', 'Froyo']

and their scores are

score = [75,60,80,79,90,30]

How to write the code in Python so if I want to know the fourth highest score the result is

The fourth highest score is Alpha.

Thanks in advance for your help.



Solution 1:[1]

here is one way :

sorted(zip(score, name), reverse=True)[3]

output:

>> (75, 'Alpha')

Solution 2:[2]

An alternative answer is to use a dictionary. A dictionary is better than two lists because it only uses one variable, and scores are tied to their name so you don't have to maintain matching indexes. This answer is assuming you are using python 3.7 or newer.sorted_scores contains sorted list of tuples structured (name,points).

scores = {
    "Alpha" : 75,
    "Betta" : 60,
    "Chroma" : 80,
    "Delta" : 79,
    "Echo" : 90,
    "Froyo" : 50
}
sorted_scores = sorted(scores.items(),key=lambda item: item[1])
print(f"The fourth highest score is {sorted_scores[-4][0]} with {sorted_scores[-4][1]} points.")
#reason for -4 is that sorted() returns the list lowest to highest, and -4 is the fourth from the end. To have higher scores at the top, add reverse=True as a parameter of sorted() and replace -4 with 3.

Solution 3:[3]

You could try the nlargest function from the heapq module:

from heapq import nlargest

name = ['Alpha','Betta','Chroma','Delta','Echo', 'Froyo']
score = [75,60,80,79,90,30]

*_,(_,fourth) = nlargest(4,zip(score,name)) # name of last of top 4

print(fourth) # Alpha

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eshirvana
Solution 2
Solution 3 Alain T.