Problem 1: Polynomial (100pts)
Problem
In mathematics, a polynomial is an expression consisting of indeterminates (also called variables) and coefficients, that involves only the operations of addition, subtraction, multiplication, and non-negative integer exponentiation of variables. An example of a polynomial of a single indeterminate \(x\) is \(x^2 − 4x + 7\).
We can use class
Polynomialto represent polynomials, and a list of number to represent coefficients. For example,Polynomial([a_0, a_1, ..., a_n])represents polynomial \(a\_0 + a\_1x + ... + a\_nx^n\).Implement required methods of class
Polynomialsuch that representing aPolynomialobjectPolynomial([a_0, a_1, ..., a_n])displaysPolynomial([a_0, a_1, ..., a_n]), printing it displaysa_0 + a_1*x^1 + ... + a_n*x^nand we can directly add or multiply two polynomial objects.Note: the highest degree coefficient of a polynomial should not be 0, unless it is just \(0\).
在数学中,多项式是一个由不定元(也称为变量)和系数组成的表达式,它只涉及变量的加法、减法、乘法和非负整数幂运算。一个单不定元 \(x\) 的多项式示例如 \(x^2 − 4x + 7\)。
我们可以使用 Polynomial 类来表示多项式,并使用一个数字列表来表示系数。例如,Polynomial([a_0, a_1, ..., a_n]) 表示多项式 \(a_0 + a_1x + \dots + a_nx^n\)。
请实现 Polynomial 类的所需方法,使得表示一个 Polynomial 对象 Polynomial([a_0, a_1, ..., a_n]) 时显示 Polynomial([a_0, a_1, ..., a_n]),打印它时显示 \(a_0 + a_1 \cdot x^1 + \dots + a_n \cdot x^n\),并且我们可以直接对两个多项式对象进行加法或乘法运算。
注意:多项式的最高次系数不应为 \(0\),除非该多项式本身就是 \(0\)。
class Polynomial:
"""Polynomial.
>>> a = Polynomial([0, 1, 2, 3, 4, 5, 0])
>>> a
Polynomial([0, 1, 2, 3, 4, 5])
>>> print(a)
0 + 1*x^1 + 2*x^2 + 3*x^3 + 4*x^4 + 5*x^5
>>> b = Polynomial([-1, 0, -2, 1, -3])
>>> print(b)
-1 + 0*x^1 + -2*x^2 + 1*x^3 + -3*x^4
>>> print(a + b)
-1 + 1*x^1 + 0*x^2 + 4*x^3 + 1*x^4 + 5*x^5
>>> print(a * b)
0 + -1*x^1 + -2*x^2 + -5*x^3 + -7*x^4 + -12*x^5 + -11*x^6 + -15*x^7 + -7*x^8 + -15*x^9
>>> print(a)
0 + 1*x^1 + 2*x^2 + 3*x^3 + 4*x^4 + 5*x^5
>>> print(b) # a and b should not be changed
-1 + 0*x^1 + -2*x^2 + 1*x^3 + -3*x^4
>>> zero = Polynomial([0])
>>> zero
Polynomial([0])
>>> print(zero)
0
"""
"*** YOUR CODE HERE ***"
Hints
Hint1: You can convert numbers to strings using the
strfunction, and you can combine strings together using+.Hint2: You may find python built-in function
enumeratehelpful.
-
你可以使用
str函数将数字转换为字符串,并可以使用+将字符串组合起来。 -
你可能会发现 Python 内建函数
enumerate会有所帮助。