codingame/training/polynomial.py

43 lines
1,021 B
Python

from itertools import zip_longest
class Polynomial:
def __init__(self, *args):
if len(args) == 0:
args = (0,)
self.coeffs = args
def __repr__(self):
return 'Polynomial{}'.format(repr(self.coeffs))
def __str__(self):
xs = ('{}*x^{}'.format(self.coeffs[i], i) for i in range(len(self.coeffs)))
return ' + '.join(xs)
def __len__(self):
return len(self.coeffs) - 1
def __add__(self, other):
return Polynomial(*(x + y for x, y in zip_longest(self.coeffs, other.coeffs, fillvalue=0)))
def __sub__(self, other):
return Polynomial(*(x - y for x, y in zip_longest(self.coeffs, other.coeffs, fillvalue=0)))
def main():
p1 = Polynomial(1, 2, 3)
print(p1)
print(len(p1))
p2 = Polynomial(2, 3, 4, 5)
print(repr(p2))
print(p2)
print(len(p2))
print(p1 + p2)
print(p1 - p2)
p3 = Polynomial()
print(repr(p3))
p4 = Polynomial(0)
print(p4)
if __name__ == '__main__':
main()