← Practice
πŸ“– SortingLearning path
Browsing as guestΒ·Sign in or create a free account to save progress and use tutor tools.
LessonΒ·difficulty 3/5Β·~15 min

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: tally the values first with a Counter. Then sort nums itself (not the distinct keys) with a key that returns a two-part tuple β€” the count negated so the most frequent land first, then the value to settle ties.

Tests

  • basic frequencies
  • simple two values
  • empty list
  • tie broken ascending

✦ Stuck? Ask for a spark

Sign in or create a free account to use your monthly AI explainer allowance.

warming up
Loading editor…
Consolewaiting

$ Console output will appear here.

>_AI coach
Sign in or create a free account to chat with the tutor.