Write a function named two_level_sort that accepts a list of tuples named scores as argument. Each element in this list is of the form (Name, Marks) and represents the marks scored by a student in a test: the first element is the student’s name and the second element is his or her marks.
To create a function named two_level_sort
that sorts a list of tuples containing student names and their respective marks, you can follow these steps. The function will sort primarily by marks in descending order, and then by name in ascending order for students with the same mark.
Here's a Python implementation:
def two_level_sort(scores):
# Sort the tuples first by marks in descending order, and then by name in ascending order
sorted_scores = sorted(scores, key=lambda student: (-student[1], student[0]))
return sorted_scores
# Example usage
scores = [("Alice", 91), ("Bob", 82), ("Charlie", 82), ("Danielle", 95)]
sorted_scores = two_level_sort(scores)
print(sorted_scores)
Sorting Logic:
sorted
function is used to sort the list.key
argument accepts a lambda function which dictates the sorting criteria.-student[1]
ensures that marks are sorted in descending order (hence, the negative sign to invert the default ascending order of sorting).student[0]
ensures that names are sorted in ascending order if the marks are tied.Output:
This function can handle a list of student tuples and sort them according to the specified criteria efficiently.
Answered By