question 157 Collections & Itertools · medium
Top tags, keeping the ties
A weekly report lists the most used tags. most_common(n) cuts the list at exactly n, which is unfair when the tag in nth place is tied with others. Write top_with_ties(tags, n): return every tag whose count is at least the count of the tag in nth place, as (tag, count) pairs, most used first.
Function
top_with_ties(tags, n)tagsa list of tag texts, one entry per use
Returnsa list of
(tag, count) tuples, highest count first; equal counts keep the order the tags were first seenRules
n larger than the number of distinct tags returns them all; n of 0 or no tags returns []Examples
calltop_with_ties(['pandas', 'python', 'pandas', 'numpy', 'python', 'sqlite', 'regex', 'numpy'], 2)returns[('pandas', 2), ('python', 2), ('numpy', 2)]
calltop_with_ties(['pandas', 'python', 'pandas', 'numpy', 'python', 'sqlite', 'regex', 'numpy'], 4)returns[('pandas', 2), ('python', 2), ('numpy', 2), ('sqlite', 1), ('regex', 1)]
calltop_with_ties(['cli', 'cli', 'cli', 'rust'], 1)returns[('cli', 3)]