"""" Ex 9.4 from "A primer on... Implement the Parabola class as a subclass of the general Polynomial class introduced earlier, and Line as a subclass of Parabola. """ import numpy as np class Polynomial: """ class implementation of a polynomial, using a list to represent the polynomial coefficients. """ def __init__(self, coefficients): self.coeff = coefficients def __call__(self, x): s = 0 for i in range(len(self.coeff)): s += self.coeff[i]*x**i return s def __add__(self, other): # return self + other # start with the longest list and add in the other: if len(self.coeff) > len(other.coeff): coeffsum = self.coeff[:] # copy! for i in range(len(other.coeff)): coeffsum[i] += other.coeff[i] else: coeffsum = other.coeff[:] # copy! for i in range(len(self.coeff)): coeffsum[i] += self.coeff[i] return Polynomial(coeffsum) def __sub__(self, other): # return self - other if len(self.coeff) > len(other.coeff): #copy self, subtract other coeffdiff = self.coeff[:] # copy! for i in range(len(other.coeff)): coeffdiff[i] -= other.coeff[i] else: #other is longest, needs some care to avoid index error coeffdiff = [0] * len(other.coeff) #list of zeros, same length as other for i in range(len(self.coeff)): #fill first entries with values from self, rest remain zero coeffdiff[i] = self.coeff[i] for i in range(len(other.coeff)): #subtract coefficients from other coeffdiff[i] -= other.coeff[i] return Polynomial(coeffdiff) def __str__(self): s = '' for i in range(0, len(self.coeff)): if self.coeff[i] != 0: s += f' + {self.coeff[i]:g}*x^{i:g}' # fix layout (many special cases): s = s.replace('+ -', '- ') s = s.replace(' 1*', ' ') s = s.replace('x^0', '1') s = s.replace('x^1 ', 'x ') if s[0:3] == ' + ': # remove initial + s = s[3:] if s[0:3] == ' - ': # fix spaces for initial - s = '-' + s[3:] return s class Parabola(Polynomial): def __init__(self, c0, c1, c2): super().__init__([c0, c1, c2]) def table(self, L, R, n): """Return a table with n points for L <= x <= R.""" s = '' for x in np.linspace(L, R, n): y = self(x) s += f'{x:12g} {y:12g}\n' return s class Line(Parabola): def __init__(self, c0, c1): super().__init__(c0, c1, 0) if __name__ == '__main__': p1 = Parabola(1,1,1) print(p1.table(0,1,11)) l1 = Line(1,1) print(l1.table(0,1,11)) """ Terminal> python Polynomial_hier.py 0 1 0.1 1.11 0.2 1.24 0.3 1.39 0.4 1.56 0.5 1.75 0.6 1.96 0.7 2.19 0.8 2.44 0.9 2.71 1 3 0 1 0.1 1.1 0.2 1.2 0.3 1.3 0.4 1.4 0.5 1.5 0.6 1.6 0.7 1.7 0.8 1.8 0.9 1.9 1 2 """