Frequency map with deterministic ties

Problem

Implement most_frequent(xs). Return the value with highest frequency; break ties by returning the smallest value. Return None for an empty input.

Starter code

def most_frequent(xs):
    pass
Reveal answer or reference solution
def most_frequent(xs):
    if not xs:
        return None
    counts = {}
    for x in xs:
        counts[x] = counts.get(x, 0) + 1
    return min(counts, key=lambda x: (-counts[x], x))

Public tests

  • most_frequent([3, 1, 3, 1, 2])1
  • most_frequent([])None

Local history

Loading attempts saved in this browser…

Use with your agent

Share this URL and your attempt. Ask the agent to start with a clarifying question or the smallest useful hint.

Tutor me on https://mlprep.iwase.dev/programming/data-structures/original-py-frequency/. If window.mlPrepAgent is available, read attempts for item original-py-frequency before tutoring. Inspect my attempt, keep the item ID, and do not reveal the full answer first. After a real attempt, append its record and read it back.

Appears in