I wondering symbolically how you would parse a polynomial into a function and return the derivative. What data structure would I use or method to parse the polynomial? Preferably without using any libraries, as this question could pop up in a technical interview.
polynomial-> of nth degree
def derivative(polynomial):
return derivative
Example:
f(x) = 2x^2+3x+1
f'(x) = 4x+3
I don't want a solution, this is not homework but a hint of where I would start.
If the polynomial equation is given as a list. For eg: p=[9,4,12,2] return value will be [27, 8, 12]
def derivative(p):
derv=[]
for i in range(len(p)-1):
derv.append((len(p)-i-1)*p[i])
return derv
A polynomial in a single variable can be represented simply as an array containing the coefficients. So for example 1 + 5x3 - 29x5 can be expressed as [1, 0, 0, 5, 0, -29]
. Expressed in this form the derivative is easy to compute.
suppose poly
is a python list as above. Then
deriv_poly = [poly[i] * i for i in range(1, len(poly))]
For sparse polynomial other representations are relatively easy, such as a list of pairs (coefficient, exponent)
or dictionary mapping exponents to coefficients.
Parsing the expression is more complicated but using various parsing frameworks should be easy because the grammar is comparatively simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With