Search code examples
pythonpython-3.xsymbolic-mathcalculusdifferentiation

Simple Polynomial Differentiator without external libraries


I'm trying to make a polynomial Differentiator without the use of external libraries like sympy and numpy, these are the test cases:

"3 + 1x + 2x^2" ==> "1 + 4x"
"1 + 2x + -3x^2 + 17x^17 + -1x^107" ==> "2 + -6x + 289x^16 + -107x^106"
"17x + 1x^2" ==> "17 + 2x"

However I get an list index error on line 4,when it is supposed to work.

s=input().split(' + ')
y='x'in s[0]
L=map(lambda x:map(int,x.split('x^')),s[2-y:])
print(' + '.join([s[1-y][:-1]]+['x^'.join(map(str,[a*b,b-1])).rstrip('^1')for a,b in L]))

Solution

  • It is hard to read your code when it is so compact on one line. Is there a reason you want it so compact and hard to read (are you in a coding competition?). I would recommend to spread your code out a little, then you can easily see what to do (and others can too).

    It looks like your code is not handling the constant and linear cases very well. We should also point out that a derivative is really easy if I had a list of coefficients. Maybe some functions, like:

    def list_to_poly(coef_list): 
        poly_list = [] 
        if not coef_list or coef_list==[0]: 
            poly_list.append('0') 
        if len(coef_list)>=1 and coef_list[0]: 
            poly_list.append(f'{coef_list[0]}') 
        if len(coef_list)>=2 and coef_list[1]: 
            poly_list.append(f'{coef_list[1] if coef_list[1]!=1 else ""}x') 
        poly_list.extend([f'{i if i!=1 else ""}x^{j+2}' for j,i in enumerate(coef_list[2:]) if i]) 
        return ' + '.join(poly_list) 
    
    def poly_to_list(string): 
        terms     = string.split(' + ') 
        poly_list = [] 
        for term in terms: 
            if 'x^' not in term: 
                if 'x' not in term: 
                    poly_list.append(int(term)) 
                else: 
                    linear_coef = term.split('x')[0] 
                    poly_list.append(int(linear_coef) if linear_coef else 1) 
            else: 
                coef,exp = term.split('x^') 
                for i in range(len(poly_list),int(exp)): 
                    poly_list.append(0) 
                poly_list.append(int(coef) if coef else 1) 
        return poly_list 
    
    def derivative(string): 
        poly_list  = poly_to_list(string) 
        derivative = [i*j for i,j in enumerate(poly_list)][1:] 
        d_string   = list_to_poly(derivative) 
        return d_string 
    
    print(derivative('0'))
    print(derivative('3 + 5x'))
    print(derivative('3 + x^5 + -3x^7'))