Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Polynomial:
- def __init__(self, *coeff):
- if any(coeff):
- for i in coeff:
- if isinstance(i, (tuple, list, set)):
- self._coeff = tuple(i)
- break
- else:
- self._coeff = tuple(coeff)
- else:
- self._coeff = (0,)
- def __add__(self, other):
- return Polynomial([self._coeff[i]+other._coeff[i] for i in range(len(self._coeff))])
- def __mul__(self, other):
- sTerms, oTerms, res = self._coeff, other._coeff, []
- for sInd, i in enumerate(sTerms):
- for oInd, j in enumerate(oTerms):
- ind, term = sInd+oInd, i*j
- try:
- res[ind] += term
- except IndexError:
- res.append(term)
- return Polynomial(res)
- def __call__(self, val):
- return sum([coeff*val**ind for ind, coeff in enumerate(self._coeff)])
- def __eq__(self, other):
- return self._coeff == other._coeff
- def __repr__(self):
- terms, res = self._coeff, ""
- if len(terms) == 1:
- res += f"{terms[0]}"
- else:
- for ind, coeff in enumerate(terms):
- if coeff == 0:
- continue
- elif ind == 0:
- res += f"{coeff}"
- elif ind == 1:
- res += f"{coeff}x" if abs(coeff)!=1 else "x"
- else:
- res += f"{coeff}x^{ind}" if abs(coeff)!=1 else f"x^{ind}"
- if ind != len(terms)-1:
- res += " + " if coeff>0 else " - "
- return res
- def from_iterable(iterable):
- return Polynomial(iterable)
- def get_degree(self):
- return len(self._coeff) if any(self._coeff) else 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement