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的选择。谢谢
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…