Medium: Interview Core · Problem 32 of 82

Sort with a Key

MediumLists and SortingPython

A list holds people as (name, age) tuples. Write sort_people(people) that returns a new list sorted by age, oldest first, and people of the same age sorted by name from A to Z.

[("Ann", 30), ("Bob", 25), ("Cy", 30)] becomes [("Ann", 30), ("Cy", 30), ("Bob", 25)].

Understand the problem

Look at how Python orders tuples and keys.

How does Python compare the tuples (30, "Cy") and (30, "Ann")?

  1. It compares only the first items, so they are equal
  2. It compares the first items, and only if they are equal, the second items
  3. It cannot compare tuples

Tuples are compared element by element, like words in a dictionary. The first items are equal, so the second decide: "Ann" is smaller than "Cy", so (30, "Ann") comes first.

You need age descending and name ascending. What does sorted(people, key=lambda p: (-p[1], p[0])) do?

  1. Sorts by age ascending, then name ascending
  2. Sorts by age descending, then name ascending
  3. Sorts by name only

The minus sign flips the order of the age: the oldest has the smallest -age, so it comes first. The name part stays ascending. This trick works for numbers; for text you would sort twice (see the reflect step).

Write the solution

Return a new sorted list.

def sort_people(people):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

The key function can return a tuple. What should it return so that "older" sorts as "smaller"?

Hint 2: the shape of the answer

sorted(people, key=...) where the key returns the negative age and then the name.

Reflect

Solution

def sort_people(people):
    return sorted(people, key=lambda person: (-person[1], person[0]))

Another way: sort twice, using stability

def sort_people(people):
    by_name = sorted(people, key=lambda person: person[0])
    return sorted(by_name, key=lambda person: person[1], reverse=True)

What this tests: sorted with key, lambda, tuple comparison, reverse, and stability.

Stability means that items with equal keys keep their earlier order. So you can sort by the least important key first and the most important last, as in the second solution. It works even when one of the keys is text that cannot be negated.

Why reverse=True on its own is wrong here: it would reverse both orders, putting the names in Z to A.

sorted returns a new list; list.sort() changes the list in place (and returns None).

Cost: O(n log n).

What an interviewer might ask next: The key is text and you need it descending while another key is ascending. How? (Sort twice, as in the second solution.)