输入多项式,生成多项式的一阶导数
#### Please do not use input() function!!!
import random
class process_derivative(object):
def __init__(self, polynominal):
self.polynominal = polynominal
def get_first_derivative(self):
# You should follow the example format. Do not use input()
result_two = 'your calculator result'
return "The first derivative is:" + result_two # e.g. "The first derivative is: '6*x^2+6*x+5'"
######要求:
1、输入的多项式只包含一个变量,变量可以是任意英文字母,不一定是x
2、不需要按照次数升高或降低的方式排列
3、系数需位于变量前
4、不存在次数相同的两项(输入的多项式必须是合并同类项后的结果)
######疑问:
如何判断只有一个变量?
如何分割不同的项?
如何把项的幂提取出来?
不知道下面代码能否满足你的要求:
测试结果如下:
#### Please do not use input() function!!!
import random
import re
class process_derivative(object):
def __init__(self, polynominal):
self.polynominal = polynominal
def get_first_derivative(self):
b = self.polynominal
letter = re.search('[a-zA-Z]+', b)[0]
res = re.findall(f"(\d+)\*{letter}\^*(\d*)", b)
symbol = re.findall("[+-]{1}", b)
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]
# You should follow the example format. Do not use input()
result_two = str1
return "The first derivative is:" + result_two # 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())
PAT编程(python) 1010 一元多项式求导
https://blog.csdn.net/qq_44614636/article/details/127039968