Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.

Functions as Arguments

~10 mincode completion

In Python a function is a value like any other. You can pass one to another function.

The clearest place you meet this is sorted, which takes an optional key: a function that says what to sort by.

words = ["banana", "fig", "apple"]

sorted(words)                    # ["apple", "banana", "fig"]   alphabetical
sorted(words, key=len)           # ["fig", "apple", "banana"]   by length
sorted(words, reverse=True)      # ["fig", "banana", "apple"]

Note key=len, not key=len(). You are handing over the function itself, not calling it.

lambda creates a small function inline, for when there is no built-in that does what you want:

people = [("ada", 36), ("grace", 45)]
sorted(people, key=lambda person: person[1])    # sort by the second item

Read lambda person: person[1] as "given a person, use their second element".

Your task:

Write sort_by_score(records) that sorts a list of (name, score) pairs from highest score to lowest and returns the sorted list.

Example Tests

Highest score comes first

Input: {"records":[["ada",70],["grace",95],["alan",82]]}

Expected: [["grace",95],["alan",82],["ada",70]]

An already sorted list is left in order

Input: {"records":[["a",9],["b",5]]}

Expected: [["a",9],["b",5]]

A single record comes back unchanged

Input: {"records":[["solo",1]]}

Expected: [["solo",1]]

Python
def sort_by_score(records):
    """
    Sort (name, score) pairs by score, highest first.

    Args:
        records: a list of [name, score] pairs

    Returns:
        The same pairs, ordered from highest score to lowest.
    """
    # YOUR CODE HERE
    pass

Run your code to see results

⌘↵ runs against the visible tests

Loading docs…