Skip to content

Commit 0214c7a

Browse files
authored
Tweak polynomial itertool recipes (GH-102880)
1 parent 7436874 commit 0214c7a

File tree

1 file changed

+13
-14
lines changed

1 file changed

+13
-14
lines changed

Doc/library/itertools.rst

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -866,6 +866,17 @@ which incur interpreter overhead.
866866
window.append(x)
867867
yield math.sumprod(kernel, window)
868868

869+
def polynomial_from_roots(roots):
870+
"""Compute a polynomial's coefficients from its roots.
871+
872+
(x - 5) (x + 4) (x - 3) expands to: x³ -4x² -17x + 60
873+
"""
874+
# polynomial_from_roots([5, -4, 3]) --> [1, -4, -17, 60]
875+
expansion = [1]
876+
for r in roots:
877+
expansion = convolve(expansion, (1, -r))
878+
return list(expansion)
879+
869880
def polynomial_eval(coefficients, x):
870881
"""Evaluate a polynomial at a specific value.
871882

@@ -876,20 +887,8 @@ which incur interpreter overhead.
876887
n = len(coefficients)
877888
if n == 0:
878889
return x * 0 # coerce zero to the type of x
879-
powers = map(pow, repeat(x), range(n))
880-
return math.sumprod(reversed(coefficients), powers)
881-
882-
def polynomial_from_roots(roots):
883-
"""Compute a polynomial's coefficients from its roots.
884-
885-
(x - 5) (x + 4) (x - 3) expands to: x³ -4x² -17x + 60
886-
"""
887-
# polynomial_from_roots([5, -4, 3]) --> [1, -4, -17, 60]
888-
roots = list(map(operator.neg, roots))
889-
return [
890-
sum(map(math.prod, combinations(roots, k)))
891-
for k in range(len(roots) + 1)
892-
]
890+
powers = map(pow, repeat(x), reversed(range(n)))
891+
return math.sumprod(coefficients, powers)
893892

894893
def iter_index(iterable, value, start=0):
895894
"Return indices where a value occurs in a sequence or iterable."

0 commit comments

Comments
 (0)