I tried sorting this challenge in so many ways but this time apparently my script is sorting the wrong way this time.
The challenge consists in you inputing the students name and score then the script must output the name of the student with the second lowest score, and if there's students with the score as the same value, output their names as well. But apparently it is sorting the wrong way.
This is my code:
score_list = []
for n in range(int(input())):
name = input()
score = float(input())
st_score = [name, score]
score_list.append(st_score)
sortedscore = sorted(score_list, key=lambda x: x[1])
secondguy = []
second_low = sortedscore[1][1]
for i in range(len(sortedscore)):
if sortedscore[i][1] == second_low:
secondguy.append(sortedscore[i])
for j in range (len(secondguy)):
student = secondguy[j][0]
print(student)
The given input was: 5 Harry 37.21 Berry 37.21 Tina 37.2 Akriti 41 Harsh 39
Expected Output was: Berry Harry
But actually the returned output was: Harry Berry
And it is sorting the elements this way:
[['Tina', 37.2], ['Harry', 37.21], ['Berry', 37.21], ['Harsh', 39.0], ['Akriti', 41.0]]
So what exactly is making this script dont give the correct response?
key=lambda x: x[1],x[0]to sort byvalueandname. You could also keep it as dictionary with lists{ 37.21: ["Harry", "Berry"], ...}for item in sortedscore:withoutrange(len(..))print()names directly in second loop without creating listsecondguyand using third loop.()-key=lambda x:(x[1],x[0])