在Python中找到多项式的导数

3

我在这项任务中遇到了问题。我需要打印多项式,这是用户的输入。(我对此也有疑问,因为它可以是任意次数的多项式,我不太确定如何打印它。) 任务的第二部分是找到这个多项式的导数。我尝试通过询问用户多项式的次数和系数,然后创建一个列表来完成这个操作,但我不认为这是一个好方法,请帮助我!

我有类似于这样的东西:

n = int(input("What is a degree of poly: "))
lista = []
for i in range (n+1):
    a = int(input("What are the coefficients "))
    lista.append(a)

lista1 = []
b = n
d = 0
for k in range (n+1):
    c = int(lista[d])*int(b)
    lista1.append(c)
    b = b - 1
    d = d + 1

print(lista1)

4
你可以查看 sympy 模块。它具有表示多项式、求导以及通过 latex 显示多项式等功能。还有许多其他功能。 - Bill Bell
1
我认为这是一个相当合理的开始方式。你具体卡在哪里了?你有一些代码可以发布吗?此外,@BillBell对sympy的+1:这是一个已经有好的解决方案的问题。但如果你是为了课程或学习经验而做这个,你可能不想走那条路。再次强调,听起来你已经有了一个很好的开始思路... - Z4-tier
我不知道如何打印它,我现在更新了我的问题并添加了代码@Z4-tier。 - ArthurMorgan
我的回答有帮助吗? - Sanjit Sarda
3个回答

1
如果你是为了课程或者学习而进行编程,并且想要避免使用 sympy ,而是自己编写代码,那么你已经迈出了良好的第一步。唯一可以建议的是,你可能希望以更整洁的格式输出结果。类似这样的格式可能会有所帮助:
deriv = ''
poly = ''
for k in range(n):
    poly += str(lista[k]) + "x^" + str(n-k) + " + "
    deriv += str(lista1[k]) + "x^" + str(n-k-1) + " + "
poly += str(lista[-1])
deriv = deriv.rstrip('x^0 +')

print("Input Polynomial: " + poly)
print("Derivative: " + deriv)

非常感谢,我是在上课时完成的,所以使用sympy并不是一个真正的选择 :) - ArthurMorgan
很高兴能帮忙。我发布的代码块并不完美(不能很好地处理零或负值),因此您可能需要进行一些更改来处理这些边缘情况。格式化和打印可能比您要解决的实际问题更难 :) - Z4-tier

0

正如您之前提到的,由于这是一个课程,您不能使用任何模块,因此这里有一些不使用模块的代码,尽管我没有费心去注释,但有一些疯狂(在某些情况下是不必要的)的替换哈哈。

但无论如何,这就是它:

class Polynomial:

    def __init__(self, input_str):
        self.polynomial_display_string = input_str.replace('**', '^').replace('*', '').replace("x^1+", "x+")\
            .replace("x^1-", "x-").replace('+0', '').replace('-0', '')\
            .replace('+-', '-').replace('-+', '-').replace('--', '+').replace('--', '+')
        self.expression_str = self.polynomial_display_string.replace('^', '**').replace('x', '*x')\
            .replace("x+", "x^1+").replace("x-", "x^1-").replace(' ', '').replace('-+', '-').replace('-', '+-')

    def derivative(self):
        if '+' not in self.expression_str:
            if "x" in self.expression_str:
                constant_multiplier = int(self.expression_str.split('*x**')[0])
                power = int(self.expression_str.split('*x**')[1])
                derivative = (str(constant_multiplier*power) + "*x^" + str(power-1))
                return Polynomial(derivative)
            else:
                return Polynomial('0')
        elif self.expression_str[0] == '+' and not self.expression_str.count('+') > 1:
            constant_multiplier = int(self.expression_str[1:].split('*x**')[0])
            power = int(self.expression_str[1:].split('*x**')[1])
            derivative = (str(constant_multiplier * power) + "*x^" + str(power - 1))
            return Polynomial(derivative)
        else:
            terms = list(filter(None, self.expression_str.split('+')))
            final_str = ""
            for term in terms:
                poly_object = Polynomial(term)
                final_str += "+" + str(poly_object.derivative().expression_str)
            final_str = final_str[1:] if final_str[0] in ['+', '-', ' '] else final_str
            return Polynomial(final_str.replace('++', '+').replace('+-', '-').replace('-+', '-').replace('--', '-')
                              .replace('+', ' + ').replace('-', ' - '))


poly = Polynomial(input('Enter a polynomial'))
print(poly.polynomial_display_string)
print(poly.derivative().polynomial_display_string)

与OP提出的解决方案相比,这个方案非常复杂。如果您添加一些详细信息来解释这种复杂性所带来的好处,并且可能附上有关如何实现它的详细信息,那么这可能会有所帮助。为什么是一个类?为什么要递归定义?如果它确实抽象了一个多项式,那么可以在多项式上执行的所有其他操作在哪里?我还可以告诉您,实现一个__str____repr__方法要比此实例级别的display_string更符合Pythonic。 - Z4-tier
是的,你说得对。一旦我明白了它,我就想,我为什么要做这个啊,哈哈。 - Sanjit Sarda

-1
你需要使用一个叫做sympy的模块。首先,你需要执行以下命令:pip install sympy。如果这个命令不能正常工作,请在评论中说明你使用的编辑器,我可能能够提供帮助。
然后,你可以运行下面这段代码,它会通过注释来解释自己,并且我已经测试过了。
import sympy as sp  # Import sympy

x = sp.Symbol('x')  # Makes a new symbol: x

degree = int(input("Degree of Polynomial"))  # get the degree of the polynomial

polynomial = 0  # Start with nothing in the polynomial and slowly add to it

for power in range(degree+1):  # degree + 1 is so that we loop it once more that number of degrees to get x^0 term
    coefficient = int(input(("What is the coefficient of the x^" + str(power) + " term")))
    # Get the coefficient of the term
    if coefficient != 0:  # we do not want to print 0*x^4 or something like that hence only add to the poly if not 0
        polynomial += coefficient*x**power  # coefficient*x^power: Pretty self explanatory

polynomialString = str(polynomial).replace('**', '^')  # Replace pythons symbol for power: ** with ^

print("Your Polynomial is", polynomialString)  # Print the polynomial

derivative = sp.diff(polynomial, x)  # Differentiate the polynomial
derivativeStr = str(derivative).replace('**', '^')  # derivative after replacing ** with ^ 

print("The derivative of ", polynomialString, " is ", derivativeStr)  # Prints the derivative


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接