Advertisement
Programmin-in-Python

Python program that implements Polynomials

Dec 4th, 2021
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. class Polynomial:
  2.     def __init__(self, *coeff):
  3.         if any(coeff):
  4.             for i in coeff:
  5.                 if isinstance(i, (tuple, list, set)):
  6.                     self._coeff = tuple(i)
  7.                     break
  8.             else:
  9.                 self._coeff = tuple(coeff)
  10.         else:
  11.             self._coeff = (0,)
  12.  
  13.     def __add__(self, other):
  14.         return Polynomial([self._coeff[i]+other._coeff[i] for i in range(len(self._coeff))])
  15.  
  16.     def __mul__(self, other):
  17.         sTerms, oTerms, res = self._coeff, other._coeff, []
  18.  
  19.         for sInd, i in enumerate(sTerms):
  20.             for oInd, j in enumerate(oTerms):
  21.                 ind, term = sInd+oInd, i*j
  22.  
  23.                 try:
  24.                     res[ind] += term
  25.                 except IndexError:
  26.                     res.append(term)
  27.  
  28.         return Polynomial(res)
  29.  
  30.     def __call__(self, val):
  31.         return sum([coeff*val**ind for ind, coeff in enumerate(self._coeff)])
  32.  
  33.     def __eq__(self, other):
  34.         return self._coeff == other._coeff
  35.  
  36.     def __repr__(self):
  37.         terms, res = self._coeff, ""
  38.  
  39.         if len(terms) == 1:
  40.             res += f"{terms[0]}"
  41.         else:
  42.             for ind, coeff in enumerate(terms):
  43.                 if coeff == 0:
  44.                     continue
  45.                 elif ind == 0:
  46.                     res += f"{coeff}"
  47.                 elif ind == 1:
  48.                     res += f"{coeff}x" if abs(coeff)!=1 else "x"
  49.                 else:
  50.                     res += f"{coeff}x^{ind}" if abs(coeff)!=1 else f"x^{ind}"
  51.  
  52.                 if ind != len(terms)-1:
  53.                     res += " + " if coeff>0 else " - "
  54.         return res
  55.  
  56.     def from_iterable(iterable):
  57.         return Polynomial(iterable)
  58.  
  59.     def get_degree(self):
  60.         return len(self._coeff) if any(self._coeff) else 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement