From ac1fb7ad5edbc806be572b2e3c1345eeebed449b Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Fri, 28 Apr 2023 11:37:12 -0500 Subject: [PATCH 1/2] Functional version that better demonstrates iterator chaining --- Doc/library/itertools.rst | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index e57c393a6b370b..c3bea377551029 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -789,6 +789,7 @@ which incur interpreter overhead. .. testcode:: import collections + import functools import math import operator import random @@ -1092,10 +1093,8 @@ The following recipes have a more mathematical flavor: (x - 5) (x + 4) (x - 3) expands to: x³ -4x² -17x + 60 """ # polynomial_from_roots([5, -4, 3]) --> [1, -4, -17, 60] - expansion = [1] - for r in roots: - expansion = convolve(expansion, (1, -r)) - return list(expansion) + factors = zip(repeat(1), map(operator.neg, roots)) + return list(functools.reduce(convolve, factors, [1])) def polynomial_eval(coefficients, x): """Evaluate a polynomial at a specific value. From 95ab9e3f9e5ca3a08e99f4610dfb9b76c10bcf09 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Fri, 28 Apr 2023 11:41:30 -0500 Subject: [PATCH 2/2] Be consistent with use of repeat(). --- Doc/library/itertools.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index c3bea377551029..a0d794017e2602 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -1083,7 +1083,7 @@ The following recipes have a more mathematical flavor: # convolve(data, [1, -2, 1]) --> 2nd finite difference (2nd derivative) kernel = tuple(kernel)[::-1] n = len(kernel) - padded_signal = chain(repeat(0, n-1), signal, [0] * (n-1)) + padded_signal = chain(repeat(0, n-1), signal, repeat(0, n-1)) for window in sliding_window(padded_signal, n): yield math.sumprod(kernel, window)