无需外部库的简单多项式微分器

问题描述 投票:0回答:1

我试图在不使用外部库(如sympy和numpy)的情况下制作一个多项式微分器,这些是测试用例。

"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"

然而我在第4行得到一个列表索引错误,而它应该是工作的。

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]))
python python-3.x symbolic-math calculus differentiation
1个回答
2
投票

你的代码在一行上如此紧凑,很难读懂。有什么原因让你的代码如此紧凑,难以阅读(你是在参加编码比赛吗?)。我建议把你的代码散开一点,这样你就可以很容易地看到该做什么(别人也可以)。

看起来你的代码没有很好地处理常数和线性情况。我们还应该指出,如果我有一个系数列表,导数真的很容易。也许有些函数,比如。

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'))
© www.soinside.com 2019 - 2024. All rights reserved.