From 04e03f496cf7da48ce4f545b41579d7d45f59ad2 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Sat, 20 Nov 2021 10:04:37 -0600 Subject: bpo-45851: Avoid full sort in statistics.multimode() (#29662) Suggested by Stefan Pochmann. --- Lib/statistics.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Lib/statistics.py b/Lib/statistics.py index e67c517..4f3ab49 100644 --- a/Lib/statistics.py +++ b/Lib/statistics.py @@ -609,9 +609,11 @@ def multimode(data): >>> multimode('') [] """ - counts = Counter(iter(data)).most_common() - maxcount, mode_items = next(groupby(counts, key=itemgetter(1)), (0, [])) - return list(map(itemgetter(0), mode_items)) + counts = Counter(iter(data)) + if not counts: + return [] + maxcount = max(counts.values()) + return [value for value, count in counts.items() if count == maxcount] # Notes on methods for computing quantiles -- cgit v0.12