Home > front end >  Find the third largest score from the list of students and scores using Python
Find the third largest score from the list of students and scores using Python

Time:03-20

Using the given lists given, how do I find the name who has the third largest score?

the data is:

names = [Andi, Budi, Charlie, Dilan, Echa]
score = [80, 80, 80, 100, 90]

CodePudding user response:

You can do:

names = ['Andi', 'Budi', 'Charlie', 'Dilan', 'Echa']
scores = [80, 80, 80, 100, 90]

print(sorted(zip(names, scores), key=lambda x: x[1])[-3][0])

output:

Charlie

Explanation:
With .zip you zip those lists together, then you sort them based on second item in the tuple which is the score. Til now you have a sorted list of tuples. You want the third highest score so [-3] and because you need the name of the person [0].


If the scores are [80, 80, 80, 100, 90], it gives you the first person encountered in that index. If you need all of them, You need a second iteration too see all persons have that score:

names = ['Andi', 'Budi', 'Charlie', 'Dilan', 'Echa']
scores = [80, 80, 80, 100, 90]

sorted_list = sorted(zip(names, scores), key=lambda x: x[1])
third_highest_score = sorted_list[-3][1]
print([name for name, score in sorted_list if score == third_highest_score])

output:

['Andi', 'Budi', 'Charlie']

CodePudding user response:

For another approach, you may use following. First a dictionary is created from two list. Then, it was ordered thanks to "Counter".

from collections import Counter

names = ["Andi", "Budi", "Charlie", "Dilan", "Echa"]  
scores = [80, 80, 80, 100, 90]

sample_dict = {}

for name in names:
    for score in scores:
        sample_dict[name] = score
        scores.remove(score)
        break

k = Counter(sample_dict)

best_3 = k.most_common(3)

print(best_3)


for i in best_3:
    print(i[0]," :",i[1]," ")

see output:

Dilan : 100 Echa : 90 Andi : 80

print(best_3[2]) # gives 3rd best one.

CodePudding user response:

One approach is to (1) sort unique scores, (2) take the nth highest score, and (3) to keep exclusively those names which correspond to the nth highest score when iterating over both lists.

Example:

names = ['Andi', 'Budi', 'Charlie', 'Dilan', 'Echa']
scores = [80, 80, 80, 100, 90]
nth_highest = 3

sorted_unique_scores = sorted(list(set(scores)))  #(1)
max_nth_highest = - len(sorted_unique_scores)
nth_highest_score = sorted_unique_scores[max(- nth_highest, max_nth_highest)]  #(2)
filtered_names = [name for name, score in zip(names, scores) if score == nth_highest_score]  #(3)
  • Related