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 key1from functools import cmp_to_key2 # A comparator returns negative if a comes first, positive if b does, 0 if equal3def compare(a, b): # Compare by length: shorter strings come first4 return len(a) - len(b)5 # Words of lengths 5, 2, 6 and 36words = ["apple", "hi", "banana", "cat"]# sorted() only accepts key=, so wrap compare with cmp_to_key7sorted_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. 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