# Untitled

a guest
Dec 2nd, 2019
116
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. import itertools as it
2.
3. class MyPolynomial(object):
4.   def __init__(self, *coefficients):
5.     self.coefficients = list(coefficients)
6.     self._priv = None
7.
8.   def __eq__(self, y):
9.     return str(self) == str(y)
10.
11.
12.   def __repr__(self):
13.     if len(self.coefficients) == 0:
14.       return '{}({})'.format(
15.         self.__class__.__name__, '0'
16.         )
17.     if sum(self.coefficients) == 0:
18.       return '{}({})'.format(
19.         self.__class__.__name__, '0'
20.         )
21.     return '{}({})'.format(
22.       self.__class__.__name__, ', '.join((str(x) for x in self.coefficients))
23.       )
24.
26.     n = len(self.coefficients)
27.     p = len(other.coefficients)
28.     if (n >= p):
29.       new_coefficients = [self.coefficients[i] for i in range(n)]
30.       for i in range(p):
31.         new_coefficients[i] += other.coefficients[i]
32.     if (p >= n):
33.       new_coefficients = [other.coefficients[i] for i in range(p)]
34.       for i in range(n):
35.         new_coefficients[i] += self.coefficients[i]
36.     return MyPolynomial(*new_coefficients)
37.
39.     for i, x in enumerate(self.coefficients):
40.       self.coefficients[i] += other.coefficients[i]
41.     return self
42.
43.   def __str__(self):
44.     out = ''
45.     size = len(self.coefficients)
46.     for i in range(size):
47.         if self.coefficients[i] != 0:
48.             out += ' + %gx^%d' % (self.coefficients[i],i)
49.
50.     out = out.replace('+ -', '- ')
51.     out = out.replace('x^0', '1')
52.     out = out.replace(' 11 ', ' 1 ')
53.     if out[0:3] == ' + ':
54.         out = out[3:]
55.     if out[0:3] == ' - ':
56.         out = '-' + out[3:]
57.     if len(out) == 0:
58.       return '0'
59.     return out
60.
61.   def from_iterable(iterables):
62.     return MyPolynomial(*iterables)
63.
64.   def degree(self):
65.     if len(self.coefficients) == 0:
66.       return 0
67.     if sum(self.coefficients) == 0:
68.       return 0
69.     i = 1
70.     iterator = len(self.coefficients)-1
71.     print("iter:"+str(iterator))
72.     for x in self.coefficients:
73.       if self.coefficients[iterator] == 0:
74.         i = i + 1
75.       else:
76.         break
77.       iterator = iterator - 1
78.     return len(self.coefficients) - i
79.
80.
81. print(repr(MyPolynomial(2)+MyPolynomial(3,4)))
82. assert MyPolynomial(5, 8) == MyPolynomial(2, 4) + MyPolynomial(3, 4)
83.
84. mp1 = MyPolynomial(2, 4)
85. mp2 = MyPolynomial(3, 4)
86. mp3 = MyPolynomial(5, 8)
87. mp1 += mp2
88. assert mp3 == mp1
RAW Paste Data