summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRaymond Hettinger <rhettinger@users.noreply.github.com>2022-08-21 14:41:29 (GMT)
committerGitHub <noreply@github.com>2022-08-21 14:41:29 (GMT)
commit0e28a3a50ff9c612a2a745907ebcb30911fd51e8 (patch)
tree913ea01ce6c274dc252c1b61704baece950d29c3
parenteea8f42deddb3b6fec80984e7557b1f0c4578b62 (diff)
downloadcpython-0e28a3a50ff9c612a2a745907ebcb30911fd51e8.zip
cpython-0e28a3a50ff9c612a2a745907ebcb30911fd51e8.tar.gz
cpython-0e28a3a50ff9c612a2a745907ebcb30911fd51e8.tar.bz2
Add polynomial_from_roots() to the itertools recipes (#96102)
-rw-r--r--Doc/library/itertools.rst19
1 files changed, 19 insertions, 0 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
index 55a4c90..c35ff8c 100644
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -800,6 +800,18 @@ which incur interpreter overhead.
window.append(x)
yield sum(map(operator.mul, 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]
+ roots = list(map(operator.neg, roots))
+ return [
+ sum(map(math.prod, combinations(roots, k)))
+ for k in range(len(roots) + 1)
+ ]
+
def flatten(list_of_lists):
"Flatten one level of nesting"
return chain.from_iterable(list_of_lists)
@@ -1137,6 +1149,13 @@ which incur interpreter overhead.
>>> list(convolve(data, [1, -2, 1]))
[20, 0, -36, 24, -20, 20, -20, -4, 16]
+ >>> polynomial_from_roots([5, -4, 3])
+ [1, -4, -17, 60]
+ >>> factored = lambda x: (x - 5) * (x + 4) * (x - 3)
+ >>> expanded = lambda x: x**3 -4*x**2 -17*x + 60
+ >>> all(factored(x) == expanded(x) for x in range(-10, 11))
+ True
+
>>> list(flatten([('a', 'b'), (), ('c', 'd', 'e'), ('f',), ('g', 'h', 'i')]))
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']