Custom Comparator in Python

Level 4191 keystrokes

This uses cmp_to_key to turn a comparison function into a sort key, sorting the words by length.

Python code

# cmp_to_key turns a two-argument comparison function into a sort key
1from functools import cmp_to_key
2
# A comparator returns negative if a comes first, positive if b does, 0 if equal
3def compare(a, b):
# Compare by length: shorter strings come first
4 return len(a) - len(b)
5
# Words of lengths 5, 2, 6 and 3
6words = ["apple", "hi", "banana", "cat"]
# sorted() only accepts key=, so wrap compare with cmp_to_key
7sorted_words = sorted(words, key=cmp_to_key(compare))
# Prints ['hi', 'cat', 'apple', 'banana']
8print(sorted_words)

Output

['hi', 'cat', 'apple', 'banana']
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 8
  • _× 6
  • (× 6
  • )× 6
  • ,× 5
  • =× 3
  • -× 1
  • :× 1
  • [× 1
  • ]× 1

More Python examples at level 4

← Python typing practice