Python问题:在不使用python中库的情况下求导

截止日期12.16。使用函数对输入的多项式求一阶导,多项式不一定降次排列,次数为非负数,求导后按照原顺序排列,用户输入如"3x^6+5x+3",程序输出"18*x^5+x"
目前思路是在加号处split,切开后再单个处理,最后再用加号连接,但是对既有加号又有减号的多项式,没有办法,无法处理。

正则库也不能用吗?如果能那就用re.split(),不能那就纯手工:
def judge(express):
    try :
        float(express)
    except :
        return False
    return True

def com(s):
    if '^' in s:
        t = s.split('x^')
        rest = int(t[0] or '1') * int(t[1])
        item = str(rest) +'x' if t[1] == '2' else str(rest) + 'x^' + str(int(t[1]) - 1)
    elif 'x' in s:
        item = s.replace('x', '')
        item =  '1' if item == "" else item 
    else:
        item = ''    
    return item

def dif(express):
    if judge(express):
        return '0' 
    res = ''
    for i in express.split('+'):
        sym1 = '+'
        res_ = ''
        if '-' not in i:
            res_ = com(i)        
        else:
            sym2 = '-'
            lst = [i] if i.find(sym2) == 0 else i.split('-')
            for j in lst:                
                item = com(j)
                res_ += (item +sym2) if item else item
            res_ = res_[:-1]
        if res_:        
            res += res_ + sym1
        return res[:-1] if res[:-1] else '0'


s1 = '5'
s2 = '-5'
s3 = '5x'
s4 = '-5x^3'
s5 = '3x^6-4x^5-3x^4-2x^3-5x^2-5x+3'
s6 = '3x^6-5' 
l = [s1, s2, s3, s4, s5, s6]

for i in l:    
    res = dif(i)
    print(res)
--result
0
0
5
-15x^2
18x^5-20x^4-12x^3-6x^2-10x-5
18x^5

一元多项式求导
https://blog.csdn.net/weixin_45918830/article/details/119578360

代码如下,望采纳

#coding:utf-8
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('2x^3+3*x^2+5*x+1')
print(a.get_first_derivative())

已经帮你完成代码如下,无第3方库使用,望采纳

# 定义一个函数,用于求一阶导
def derivative(polynomial: str) -> str:
  # 定义一个列表,用于存储求导后的多项式的各项
  items = []
  # 将多项式以"+"为分隔符分割成一个个单项式
  monomials = polynomial.split("+")
  for monomial in monomials:
    # 如果单项式不是空字符串,则进行求导
    if monomial:
      # 判断单项式是否包含"x"
      if "x" in monomial:
        # 如果包含"x",则拆分出系数和次数
        coef, power = monomial.split("x^")
        # 如果系数是空字符串,则表示系数为1
        if coef == "":
          coef = "1"
        # 如果次数是空字符串,则表示次数为1
        if power == "":
          power = "1"
        # 求一阶导
        coef, power = str(int(coef) * int(power)), str(int(power) - 1)
        # 如果次数为0,则不输出"x^0"
        if power == "0":
          items.append(coef)
        else:
          items.append(f"{coef}*x^{power}")
      # 如果单项式不包含"x",则表示该项为常数项,不做求导
      else:
        items.append(monomial)
  # 返回求导后的多项式
  return "+".join(items)

# 测试函数
print(derivative("3x^6+5x+3"))  # 输出:18*x^5+x
print(derivative("x^3+x^2+3x"))  # 输出:3*x^2+2*x^1+3