@@ -800,6 +800,18 @@ which incur interpreter overhead.
800800 window.append(x)
801801 yield sum(map(operator.mul, kernel, window))
802802
803+ def polynomial_from_roots(roots):
804+ """Compute a polynomial's coefficients from its roots.
805+
806+ (x - 5) (x + 4) (x - 3) expands to: x³ -4x² -17x + 60
807+ """
808+ # polynomial_from_roots([5, -4, 3]) --> [1, -4, -17, 60]
809+ roots = list(map(operator.neg, roots))
810+ return [
811+ sum(map(math.prod, combinations(roots, k)))
812+ for k in range(len(roots) + 1)
813+ ]
814+
803815 def flatten(list_of_lists):
804816 "Flatten one level of nesting"
805817 return chain.from_iterable(list_of_lists)
@@ -1137,6 +1149,13 @@ which incur interpreter overhead.
11371149 >>> list (convolve(data, [1 , - 2 , 1 ]))
11381150 [20, 0, -36, 24, -20, 20, -20, -4, 16]
11391151
1152+ >>> polynomial_from_roots([5 , - 4 , 3 ])
1153+ [1, -4, -17, 60]
1154+ >>> factored = lambda x : (x - 5 ) * (x + 4 ) * (x - 3 )
1155+ >>> expanded = lambda x : x** 3 - 4 * x** 2 - 17 * x + 60
1156+ >>> all (factored(x) == expanded(x) for x in range (- 10 , 11 ))
1157+ True
1158+
11401159 >>> list (flatten([(' a' , ' b' ), (), (' c' , ' d' , ' e' ), (' f' ,), (' g' , ' h' , ' i' )]))
11411160 ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
11421161
0 commit comments