Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import itertools as it
- class MyPolynomial(object):
- def __init__(self, *coefficients):
- self.coefficients = list(coefficients)
- self._priv = None
- def __eq__(self, y):
- return str(self) == str(y)
- def __repr__(self):
- if len(self.coefficients) == 0:
- return '{}({})'.format(
- self.__class__.__name__, '0'
- )
- if sum(self.coefficients) == 0:
- return '{}({})'.format(
- self.__class__.__name__, '0'
- )
- return '{}({})'.format(
- self.__class__.__name__, ', '.join((str(x) for x in self.coefficients))
- )
- def __str__(self):
- out = ''
- size = len(self.coefficients)
- for i in range(size):
- if self.coefficients[i] != 0:
- out += ' + %gx^%d' % (self.coefficients[i],i)
- out = out.replace('+ -', '- ')
- out = out.replace('x^0', '1')
- out = out.replace(' 11 ', ' 1 ')
- if out[0:3] == ' + ':
- out = out[3:]
- if out[0:3] == ' - ':
- out = '-' + out[3:]
- if len(out) == 0:
- return '0'
- return out
- def from_iterable(iterables):
- return MyPolynomial(*iterables)
- def degree(self):
- if len(self.coefficients) == 0:
- return 0
- if sum(self.coefficients) == 0:
- return 0
- i = 1
- iterator = len(self.coefficients)-1
- print("iter:"+str(iterator))
- for x in self.coefficients:
- if self.coefficients[iterator] == 0:
- i = i + 1
- else:
- break
- iterator = iterator - 1
- return len(self.coefficients) - i
- w = MyPolynomial(0, 1, 0)
- print(w.degree())
- assert MyPolynomial(5, 4).degree() == 1
- assert MyPolynomial().degree() == 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement