diff options
author | Raymond Hettinger <rhettinger@users.noreply.github.com> | 2021-11-20 10:04:37 -0600 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-11-20 10:04:37 -0600 |
commit | 04e03f496cf7da48ce4f545b41579d7d45f59ad2 (patch) | |
tree | 5ae0640527f1632f4bb3b8364a47571a43ddc9e0 | |
parent | ef5305819ff9b283d92dbf004f977592f4e64165 (diff) | |
download | cpython-git-04e03f496cf7da48ce4f545b41579d7d45f59ad2.tar.gz |
bpo-45851: Avoid full sort in statistics.multimode() (#29662)
Suggested by Stefan Pochmann.
-rw-r--r-- | Lib/statistics.py | 8 |
1 files changed, 5 insertions, 3 deletions
diff --git a/Lib/statistics.py b/Lib/statistics.py index e67c517091..4f3ab49b40 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 |