目标描述:
输入一个多项式,返回该多项式的一阶导数多项式
输入要求:
1、输入的多项式只包含一个变量
,变量可以是任意英文字母
,不一定是x
2、不需要按照次数升高或降低的方式排列
3、系数需位于变量前
4、不存在次数相同的两项(输入的多项式必须是合并同类项后的结果)
需求示例:
输入:2*x^3+3*x^2+5*x+1 输出:6*x^2+6*x+5
代码实现:
import random import re class process_derivative(object): def __init__(self, polynominal): self.polynominal = polynominal def get_first_derivative(self): # 查找多项式变量名 letter = re.search('[a-zA-Z]+', self.polynominal) # 如果输入是常数返回0,即没有找到变量 if not letter: return 0 letter = letter[0] # 查找变量系数及幂 res = re.findall(f"(\d+)\*{letter}\^*(\d*)", self.polynominal) # 查找运算符号 symbol = re.findall("[+-]{1}", self.polynominal) str1 = '' for index, coef in enumerate(res): num = coef[0] i = coef[1] if i: coef1 = int(num) * int(i) if int(i) - 1 == 1: str2 = "{}*{}".format(coef1, letter) else: str2 = "{}*{}^{}".format(coef1, letter, int(i) - 1) else: coef1 = int(num) str2 = "{}".format(coef1) str1 += str2 if index >= 0 and index < len(symbol) and i: str1 += symbol[index] return "The first derivative is:" + str1 # e.g. "The first derivative is: '6*x^2+6*x+5'" a = process_derivative('2*x^3+3*x^2+5*x+1') print(a.get_first_derivative())
测试结果:
a = process_derivative('2*x^3+3*x^2+5*x+1') a.get_first_derivative()
'The first derivative is:6*x^2+6*x+5' • 1
a = process_derivative('2*y^3-3*y^2+1') a.get_first_derivative()
'The first derivative is:6*y^2-6*y+' • 1
a = process_derivative('10') a.get_first_derivative() • 1 • 2
0