diff options
author | Raymond Hettinger <rhettinger@users.noreply.github.com> | 2023-03-21 18:21:57 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-03-21 18:21:57 (GMT) |
commit | 0214c7ad90b0afc3d1491c96e22e48d426caf5e2 (patch) | |
tree | f2c0c5d17de6208f40438b26b52b4ff309429349 /Doc/library/itertools.rst | |
parent | 743687434c5baf01c266320b34c7a828726702a6 (diff) | |
download | cpython-0214c7ad90b0afc3d1491c96e22e48d426caf5e2.zip cpython-0214c7ad90b0afc3d1491c96e22e48d426caf5e2.tar.gz cpython-0214c7ad90b0afc3d1491c96e22e48d426caf5e2.tar.bz2 |
Tweak polynomial itertool recipes (GH-102880)
Diffstat (limited to 'Doc/library/itertools.rst')
-rw-r--r-- | Doc/library/itertools.rst | 27 |
1 files changed, 13 insertions, 14 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index 38bc369..5daadfd 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -866,6 +866,17 @@ which incur interpreter overhead. window.append(x) yield math.sumprod(kernel, window) + def polynomial_from_roots(roots): + """Compute a polynomial's coefficients from its roots. + + (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) + def polynomial_eval(coefficients, x): """Evaluate a polynomial at a specific value. @@ -876,20 +887,8 @@ which incur interpreter overhead. n = len(coefficients) if n == 0: return x * 0 # coerce zero to the type of x - powers = map(pow, repeat(x), range(n)) - return math.sumprod(reversed(coefficients), powers) - - def polynomial_from_roots(roots): - """Compute a polynomial's coefficients from its roots. - - (x - 5) (x + 4) (x - 3) expands to: x³ -4x² -17x + 60 - """ - # polynomial_from_roots([5, -4, 3]) --> [1, -4, -17, 60] - roots = list(map(operator.neg, roots)) - return [ - sum(map(math.prod, combinations(roots, k))) - for k in range(len(roots) + 1) - ] + powers = map(pow, repeat(x), reversed(range(n))) + return math.sumprod(coefficients, powers) def iter_index(iterable, value, start=0): "Return indices where a value occurs in a sequence or iterable." |