1

There are 5 students in this class whose names and grades are assembled to build the following list:

students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]]

The lowest grade of 37.2 belongs to Tina. The second lowest grade of 37.21 belongs to both Harry and Berry, so we order their names alphabetically and print each name on a new line.

Solution:

min_score = min(students, key=lambda student: student[1])

second_min_score = min(students, key=lambda student: student[1] > min_score[1])

result = []
for record in records:
     if record[1] == second_min_score[1]:
         result.append(record[0])
result = sorted(result)
for res in result:
    print(res)

second_min expected: ['Harry',37.21]
second_min coming: ['Tina', 37.2]

second_min_score = min(students, key=lambda student: student[1] > min_score[1])

Here I am trying to filter the nested list data having marks greater than the minimum to find the value of second minimum, but it doesn't seem to be working as expected, anyone can please explain the issue here. I am a newbie to python and it seems I didn't grasp the concept of lambda function correctly. I appreciate your help :)

Kraigolas
  • 5,121
  • 3
  • 12
  • 37
  • 2
    You are sorting by a boolean value "is the student better than the worst student or not". By definition *all* students except the worst are better than the worst, so you get the worst student again (since `False` compares "less" than `True`). – mkrieger1 Jun 14 '21 at 21:12
  • To sum up, the problem has nothing to do with using `lambda` correctly. – mkrieger1 Jun 14 '21 at 21:14

1 Answers1

0

You can try this approach:

  1. Order your list by grade asc. and by name alphabetically desc. (at least, that was I understood in the question). For achieving this I have based this answer made by black panda user, using the reversor class propose by him.
students = sorted(students, key=lambda x: (x[1], reversor(x[0])))
print(students)

Output:

[['Tina', 37.2], ['Harry', 37.21], ['Berry', 37.21], ['Harsh', 39], ['Akriti', 41]]
  1. Find the minimum grade in your list:
the_min = min([l[1] for l in students])
print(the_min)

Output: 37.2

  1. Remove all students who have the lowest grade:
students = list(filter(lambda x: x[1] > the_min, students))
print(students)

Output:

[['Harry', 37.21], ['Berry', 37.21], ['Harsh', 39], ['Akriti', 41]]
  1. The second lowest will be the first element in your list:
second_lowest = students[0]
second_lowest

Output: ['Harry', 37.21]

FULL CODE:

students = sorted(students, key=lambda x: (x[1], reversor(x[0])))
the_min = min([l[1] for l in students])
students = list(filter(lambda x: x[1] > the_min, students))
second_lowest = students[0]
Carmoreno
  • 1,271
  • 17
  • 29