Skip to content

Commit 417da82

Browse files
committed
feat: optimize collections.Counter.most_common() when n == 1; add tests for coverage; add NEWS file
1 parent cf71e34 commit 417da82

3 files changed

Lines changed: 24 additions & 0 deletions

File tree

Lib/collections/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -634,6 +634,9 @@ def most_common(self, n=None):
634634
if n is None:
635635
return sorted(self.items(), key=_itemgetter(1), reverse=True)
636636

637+
if n == 1:
638+
return [max(self.items(), key=_itemgetter(1))]
639+
637640
# Lazy import to speedup Python startup time
638641
global heapq
639642
if heapq is None:

Lib/test/test_collections.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2279,6 +2279,24 @@ def test_invariant_for_the_in_operator(self):
22792279
self.assertTrue(elem in c)
22802280
self.assertIn(elem, c)
22812281

2282+
def test_most_common(self):
2283+
c = Counter(a=5, b=3, c=5, d=2, e=0, f=-1)
2284+
2285+
self.assertEqual(c.most_common(), [('a', 5), ('c', 5), ('b', 3), ('d', 2), ('e', 0), ('f', -1)])
2286+
self.assertEqual(c.most_common(3), [('a', 5), ('c', 5), ('b', 3)])
2287+
self.assertEqual(c.most_common(0), [])
2288+
self.assertEqual(c.most_common(-2), [])
2289+
self.assertEqual(c.most_common(1), [('a', 5)])
2290+
2291+
# Test empty counter
2292+
empty_c = Counter()
2293+
2294+
self.assertEqual(empty_c.most_common(), [])
2295+
self.assertEqual(empty_c.most_common(3), [])
2296+
self.assertEqual(empty_c.most_common(0), [])
2297+
self.assertEqual(empty_c.most_common(-2), [])
2298+
self.assertEqual(empty_c.most_common(1), [])
2299+
22822300
def test_multiset_operations(self):
22832301
# Verify that adding a zero counter will strip zeros and negatives
22842302
c = Counter(a=10, b=-2, c=0) + Counter()
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Optimize :meth:`collections.Counter.most_common` for ``n=1`` to use
2+
:func:`max` instead of :func:`heapq.nlargest`, improving performance for
3+
the common case of finding the single most common element.

0 commit comments

Comments
 (0)