【机器学习知识点】2. 输入一个多项式,返回该多项式的一阶导数多项式

目标描述:

输入一个多项式,返回该多项式的一阶导数多项式

输入要求:

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'
a = process_derivative('2*y^3-3*y^2+1')
a.get_first_derivative()
'The first derivative is:6*y^2-6*y+'
a = process_derivative('10')
a.get_first_derivative()
0

如果内容对你有帮助,感谢点赞+关注哦!

关注下方GZH:阿旭算法与机器学习,可获取更多干货内容~欢迎共同学习交流

你可能感兴趣的:(机器学习知识点,python,多项式,一阶导数,多项式一阶导数)