Created
November 12, 2017 01:24
-
-
Save ricokahler/89152fe333441f8d6a801cad515a6c15 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Polynomial: | |
def __init__(self, coefficient, exponent, next = None): | |
self.coefficient = coefficient | |
self.exponent = exponent | |
self.next = next | |
def _add(term_a, term_b): | |
if term_a == None: | |
return term_b | |
if term_b == None: | |
return term_a | |
if term_a.exponent == term_b.exponent: | |
return Polynomial( | |
term_a.coefficient + term_b.coefficient, | |
term_a.exponent, | |
Polynomial._add(term_a.next, term_b.next) | |
) | |
if term_a.exponent > term_b.exponent: | |
return Polynomial( | |
term_a.coefficient, | |
term_a.exponent, | |
Polynomial._add(term_a.next, term_b) | |
) | |
return Polynomial( | |
term_b.coefficient, | |
term_b.exponent, | |
Polynomial._add(term_b.next, term_a) | |
) | |
def __add__(self, other): | |
return Polynomial._add(self, other) | |
def __str__(self): | |
if self.next == None: | |
next_str = '' | |
else: | |
next_str = str(self.next) | |
return ' + ' + str(self.coefficient) + 'x^' + str(self.exponent) + next_str | |
# 3x^3 + 2x^2 | |
term_3x3_2x2 = Polynomial(3, 3, Polynomial(2, 2)) | |
# 3x^2 + 5x^0 | |
term_3x2_5x0 = Polynomial(3, 2, Polynomial(5, 0)) | |
new_term = term_3x3_2x2 + term_3x2_5x0 | |
print(new_term) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment