8000 Update itertool recipe: polynomial_from_roots() (GH-103973) · python/cpython@c3453fb · GitHub
[go: up one dir, main page]

Skip to content

Commit c3453fb

Browse files
authored
Update itertool recipe: polynomial_from_roots() (GH-103973)
1 parent 81387fe commit c3453fb

File tree

1 file changed

+4
-5
lines changed

1 file changed

+4
-5
lines changed

Doc/library/itertools.rst

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -789,6 +789,7 @@ which incur interpreter overhead.
789789
.. testcode::
790790

791791
import collections
792+
import functools
792793
import math
793794
import operator
794795
import random
@@ -1082,7 +1083,7 @@ The following recipes have a more mathematical flavor:
10821083
# convolve(data, [1, -2, 1]) --> 2nd finite difference (2nd derivative)
10831084
kernel = tuple(kernel)[::-1]
10841085
n = len(kernel)
1085-
padded_signal = chain(repeat(0, n-1), signal, [0] * (n-1))
1086+
padded_signal = chain(repeat(0, n-1), signal, repeat(0, n-1))
10861087
for window in sliding_window(padded_signal, n):
10871088
yield math.sumprod(kernel, window)
10881089

@@ -1092,10 +1093,8 @@ The following recipes have a more mathematical flavor:
10921093
(x - 5) (x + 4) (x - 3) expands to: x³ -4x² -17x + 60
10931094
"""
10941095
# polynomial_from_roots([5, -4, 3]) --> [1, -4, -17, 60]
1095-
expansion = [1]
1096-
for r in roots:
1097-
expansion = convolve(expansion, (1, -r))
1098-
return list(expansion)
1096+
factors = zip(repeat(1), map(operator.neg, roots))
1097+
return list(functools.reduce(convolve, factors, [1]))
10991098

11001099
def polynomial_eval(coefficients, x):
11011100
"""Evaluate a polynomial at a specific value.

0 commit comments

Comments
 (0)
0