0PricingLogin
Competitive Programming Academy · Lesson

Custom Order with functools.cmp_to_key

Write a comparator when keys fall short.

When a key Cannot Express It

Some orders depend on comparing two items together, not one value each. For those, you write a comparator function instead of a key.

What a Comparator Returns

A comparator takes two items a and b. Return a negative number if a comes first, positive if b comes first, and zero if they tie.

def cmp(a, b):
    if a < b: return -1
    if a > b: return 1
    return 0

All lessons in this course

  1. sorted() and the key Function
  2. Sort by Multiple Fields
  3. Custom Order with functools.cmp_to_key
  4. Why Sorting First Unlocks Solutions
← Back to Competitive Programming Academy