I have polynomial coefficients. How to get a list of coefficients e.g. by multiplying 10 polynomials?
For example for two polynomials. (x 2)*(x 2) = x^2 4x 4
[1,2] * [1,2] = [1, 4, 4]
I am trying to solve a codewars task which gives me a list of roots and I have to return a polynomial. My first idea was function from numpy, poly but there is too much difference with large numbers. Thank u!
Source: https://www.codewars.com/kata/5b2d5be2dddf0be5b00000c4
My code:
import re
from numpy import poly
from math import fabs
def polynomialize(roots):
result = ''
data = list(filter(lambda x : x[0] != 0, zip(poly(roots).tolist(), range(len(roots), -1, -1))))
for coe, power in data:
if coe > 0:
result = f' {int(coe)}x^{power} '
else:
result = f'- {int(fabs(coe))}x^{power} '
result = re.sub(r'(x\^1)(?![0-9] )', 'x', result).replace('x^0', '')
result = re.sub(r'(?<![0-9])(1x)','x', result)
return result[2:] '= 0'
CodePudding user response:
This is likely related to the integer type that numpy uses in its arrays, while the inputs and the resulting coefficients may involve greater numbers than these integers can hold (wrapping around).
You could do this to get data
:
coeff = [1]
for r in roots:
coeff = [t[1] - r * t[0] for t in zip(coeff [0], [0] coeff)]
data = list(filter(lambda x : x[1] != 0,
reversed(list(enumerate(coeff)))))
for power, coe in data: # notice the pairs are in reverse compared to your loop
Also fabs
is limited to integer. I would change int(fabs(coe))
to -int(coe)
.
I submitted this solution and it was accepted:
import re
def polynomialize(roots):
coeff = [1]
for r in roots:
coeff = [t[1] - r * t[0] for t in zip(coeff [0], [0] coeff)]
data = list(filter(lambda x : x[1] != 0,
reversed(list(enumerate(coeff)))))
result = ''
for power, coe in data:
if coe > 0:
result = f' {int(coe)}x^{power} '
else:
result = f'- {-int(coe)}x^{power} '
result = re.sub(r'(x\^1)(?![0-9] )', 'x', result).replace('x^0', '')
result = re.sub(r'(?<![0-9])(1x)','x', result)
return result[2:] '= 0'
CodePudding user response:
Is it what you want?
from sympy import symbols, Poly
x = symbols("x")
pol1 = Poly(x 2)
pol = pol1 ** 2
pol.all_coeffs()
# [1, 4, 4]