在 Python 中查找多项式的导数



我对这个任务有问题。我必须打印一个多项式,这是用户的输入。(我对此也有问题,因为它可以是任何程度的多项式,而且我不确定如何打印它(。 任务的第二部分是找到这个多项式的导数。我试图通过要求用户提供这个多项式和系数的次数,然后创建一个列表来做到这一点,但我认为这不是一个好方法,所以请帮助我!

我有这样的东西:

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)

如果你是专门为一堂课做的,或者只是为了学习,并且你想避免使用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)

正如你之前提到的,你不能使用任何模块,因为它是用于类的,所以这里有一些不使用模块的代码,虽然我没有费心评论,有一些疯狂的(在某些情况下是不必要的(替换 lol。

但无论如何,这里是:

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)

你将需要使用一个名为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

最新更新