Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình Python tìm học sinh có điểm thứ hai thấp nhất từ nested list


Cho nested list students = [[name, score], ...]. In tên các học sinh có điểm thứ hai thấp nhất (second lowest grade). Nếu nhiều người, sắp xếp tên theo alphabet và in mỗi tên một dòng.

Ví dụ: [['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]] → điểm thấp nhất 36 (Tarun), thứ hai thấp nhất 37 → Amal, Bimal.

Thuật toán

  • Tìm min_mark = điểm nhỏ nhất.
  • Lọc bỏ các học sinh có điểm = min_mark.
  • Tìm min2_mark = điểm nhỏ nhất trong nhóm còn lại.
  • Lọc học sinh có điểm = min2_mark, sắp xếp tên, in ra.

Ví dụ mã nguồn

def solve(students):
    min_mark = min(x[1] for x in students)
    students = [x for x in students if x[1] > min_mark]
    min2_mark = min(x[1] for x in students)
    students = sorted([x[0] for x in students if x[1] == min2_mark])
    for x in students:
        print(x)

students = [['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]]
solve(students)
# Amal
# Bimal

Đầu vào / Đầu ra

Input:  [['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]]
Output: Amal
        Bimal