From 6c01ebcc0dfc6be22950fabb46bdc10dcb6202c9 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Wed, 5 Jun 2019 07:39:38 -0700 Subject: [PATCH] bpo-37158: Simplify and speed-up statistics.fmean() (GH-13832) --- Lib/statistics.py | 8 ++++---- .../next/Library/2019-06-04-22-25-38.bpo-37158.JKm15S.rst | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2019-06-04-22-25-38.bpo-37158.JKm15S.rst diff --git a/Lib/statistics.py b/Lib/statistics.py index 012845b8d2e..5be70e5ebf4 100644 --- a/Lib/statistics.py +++ b/Lib/statistics.py @@ -320,11 +320,11 @@ def fmean(data): except TypeError: # Handle iterators that do not define __len__(). n = 0 - def count(x): + def count(iterable): nonlocal n - n += 1 - return x - total = fsum(map(count, data)) + for n, x in enumerate(iterable, start=1): + yield x + total = fsum(count(data)) else: total = fsum(data) try: diff --git a/Misc/NEWS.d/next/Library/2019-06-04-22-25-38.bpo-37158.JKm15S.rst b/Misc/NEWS.d/next/Library/2019-06-04-22-25-38.bpo-37158.JKm15S.rst new file mode 100644 index 00000000000..4a5ec4122f9 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2019-06-04-22-25-38.bpo-37158.JKm15S.rst @@ -0,0 +1 @@ +Speed-up statistics.fmean() by switching from a function to a generator.