| 13 | |
| 14 | |
| 15 | class Polynomial: |
| 16 | def __init__(self, degree: int, coefficients: MutableSequence[float]) -> None: |
| 17 | """ |
| 18 | The coefficients should be in order of degree, from smallest to largest. |
| 19 | >>> p = Polynomial(2, [1, 2, 3]) |
| 20 | >>> p = Polynomial(2, [1, 2, 3, 4]) |
| 21 | Traceback (most recent call last): |
| 22 | ... |
| 23 | ValueError: The number of coefficients should be equal to the degree + 1. |
| 24 | |
| 25 | """ |
| 26 | if len(coefficients) != degree + 1: |
| 27 | raise ValueError( |
| 28 | "The number of coefficients should be equal to the degree + 1." |
| 29 | ) |
| 30 | |
| 31 | self.coefficients: list[float] = list(coefficients) |
| 32 | self.degree = degree |
| 33 | |
| 34 | def __add__(self, polynomial_2: Polynomial) -> Polynomial: |
| 35 | """ |
| 36 | Polynomial addition |
| 37 | >>> p = Polynomial(2, [1, 2, 3]) |
| 38 | >>> q = Polynomial(2, [1, 2, 3]) |
| 39 | >>> p + q |
| 40 | 6x^2 + 4x + 2 |
| 41 | """ |
| 42 | |
| 43 | if self.degree > polynomial_2.degree: |
| 44 | coefficients = self.coefficients[:] |
| 45 | for i in range(polynomial_2.degree + 1): |
| 46 | coefficients[i] += polynomial_2.coefficients[i] |
| 47 | return Polynomial(self.degree, coefficients) |
| 48 | else: |
| 49 | coefficients = polynomial_2.coefficients[:] |
| 50 | for i in range(self.degree + 1): |
| 51 | coefficients[i] += self.coefficients[i] |
| 52 | return Polynomial(polynomial_2.degree, coefficients) |
| 53 | |
| 54 | def __sub__(self, polynomial_2: Polynomial) -> Polynomial: |
| 55 | """ |
| 56 | Polynomial subtraction |
| 57 | >>> p = Polynomial(2, [1, 2, 4]) |
| 58 | >>> q = Polynomial(2, [1, 2, 3]) |
| 59 | >>> p - q |
| 60 | 1x^2 |
| 61 | """ |
| 62 | return self + polynomial_2 * Polynomial(0, [-1]) |
| 63 | |
| 64 | def __neg__(self) -> Polynomial: |
| 65 | """ |
| 66 | Polynomial negation |
| 67 | >>> p = Polynomial(2, [1, 2, 3]) |
| 68 | >>> -p |
| 69 | - 3x^2 - 2x - 1 |
| 70 | """ |
| 71 | return Polynomial(self.degree, [-c for c in self.coefficients]) |
| 72 | |