Sortingsorting-by-frequency
LessonΒ·difficulty 3/5Β·~15 min
Sorting: by frequency
Sorting: by frequency
sorted can sort by anything you want via a key function. Return a tuple
and Python sorts by the first element, then the second as a tiebreaker:
python
from collections import Counter
counts = Counter([1, 1, 2, 2, 2, 3]) # {1: 2, 2: 3, 3: 1}
sorted([3, 1, 2], key=lambda x: (-x, x)) # negate to sort DESCENDING
A Counter tallies how often each value appears. Negating a number flips the
sort direction, so key=(-count, value) means most frequent first, ties
broken by the smaller value.
Your task
Write frequency_sort(nums) that returns the same numbers, sorted by
frequency descending, with ties broken by the number ascending.
python
frequency_sort([1, 1, 2, 2, 2, 3]) # [2, 2, 2, 1, 1, 3]
frequency_sort([4, 4, 1]) # [4, 4, 1]
frequency_sort([]) # []
Hint: build counts = Counter(nums), then
sorted(nums, key=lambda x: (-counts[x], x)).
Tests
- basic frequencies
- simple two values
- empty list
- tie broken ascending
- two tied pairs (hidden)
- negatives (hidden)
Stuck? Ask for a spark
warming up
Loading editorβ¦
$ Console output will appear here.