diff options
author | Raymond Hettinger <rhettinger@users.noreply.github.com> | 2023-04-28 17:25:50 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-04-28 17:25:50 (GMT) |
commit | c3453fbb119c7ad916d68953f17d35668b0ff390 (patch) | |
tree | 7055b494a7143e12af0b6090930ab7104b716702 /Doc/library/itertools.rst | |
parent | 81387fe36e76438447ff2bddc36f4f5ff2c820a2 (diff) | |
download | cpython-c3453fbb119c7ad916d68953f17d35668b0ff390.zip cpython-c3453fbb119c7ad916d68953f17d35668b0ff390.tar.gz cpython-c3453fbb119c7ad916d68953f17d35668b0ff390.tar.bz2 |
Update itertool recipe: polynomial_from_roots() (GH-103973)
Diffstat (limited to 'Doc/library/itertools.rst')
-rw-r--r-- | Doc/library/itertools.rst | 9 |
1 files changed, 4 insertions, 5 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index e57c393..a0d7940 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 @@ -1082,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) @@ -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. |