SHARE
TWEET

Untitled

a guest Dec 2nd, 2019 96 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.      
  25.   def __str__(self):
  26.     out = ''
  27.     size = len(self.coefficients)    
  28.     for i in range(size):
  29.         if self.coefficients[i] != 0:
  30.             out += ' + %gx^%d' % (self.coefficients[i],i)
  31.    
  32.     out = out.replace('+ -', '- ')
  33.     out = out.replace('x^0', '1')
  34.     out = out.replace(' 11 ', ' 1 ')
  35.     if out[0:3] == ' + ':
  36.         out = out[3:]
  37.     if out[0:3] == ' - ':
  38.         out = '-' + out[3:]
  39.     if len(out) == 0:
  40.       return '0'
  41.     return out
  42.    
  43.   def from_iterable(iterables):
  44.     return MyPolynomial(*iterables)
  45.    
  46.   def degree(self):
  47.     if len(self.coefficients) == 0:
  48.       return 0
  49.     if sum(self.coefficients) == 0:
  50.       return 0
  51.     i = 1
  52.     iterator = len(self.coefficients)-1
  53.     print("iter:"+str(iterator))
  54.     for x in self.coefficients:
  55.       if self.coefficients[iterator] == 0:
  56.         i = i + 1
  57.       else:
  58.         break
  59.       iterator = iterator - 1
  60.     return len(self.coefficients) - i  
  61.    
  62.    
  63. w = MyPolynomial(0, 1, 0)
  64. print(w.degree())
  65.    
  66.  
  67. assert MyPolynomial(5, 4).degree() == 1
  68. assert MyPolynomial().degree() == 0
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top