Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

python程序书写

from collections import defaultdict
import re

P = re.compile(r'+?(-?d*)(x^?)?(d*)')

def differentiate(eq, x):
    
    derivate = defaultdict(int)
    for coef,var,exp in P.findall(eq):
        exp  = int(exp or var and '1' or '0')
        coef = int(coef!='-' and coef or coef and '-1' or '1')
        
        if exp: derivate[exp-1] += exp * coef
    
    return sum(coef * x**exp for exp,coef in derivate.items())

程序功能为对多项式求导 其中for循环中的语句能看懂 但是自己写起来会逻辑混乱,想请问一下如果自己写循环中的语句的话应该是怎样一个思路,怎么确定各参数书写的位置和and和or的选择。谢谢


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

and和or的选择全依赖你脑海中的逻辑。
代码只是你脑子中逻辑的可视化而已。所以要先想清楚,然后再写代码。
可以先在纸上把逻辑写出来,理通顺了再转换成代码。
如果代码看起来乱,有几点小建议:
1.在每行代码上面写上注释。解释每行代码干嘛的
2.if else表达式不要太长,长的话 表达式都定义为变量,就像上面的代码里的exp coef那样就很好
3.表达式里有多个 and or 的时候 可以加上括号,标明优先级。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...