-
-
Save schmit/875840d1a231526b572e to your computer and use it in GitHub Desktop.
cme193 demo: Rational class
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 Rational: | |
def __init__(self, p, q=1): | |
g = gcd(p, q) | |
self.p = p / g | |
self.q = q / g | |
def __add__(self, other): | |
p = self.p * other.q + other.p * self.q | |
q = self.q * other.q | |
return Rational(p, q) | |
def __sub__(self, other): | |
p = self.p * other.q - other.p * self.q | |
q = self.q * other.q | |
return Rational(p, q) | |
def __mul__(self, other): | |
p = self.p * other.p | |
q = self.q * other.q | |
return Rational(p, q) | |
def __div__(self, other): | |
p = self.p * other.q | |
q = self.q * other.p | |
return Rational(p, q) | |
def __repr__(self): | |
if self.q == 1: | |
return '{}'.format(self.p) | |
return '{}/{}'.format(self.p, self.q) | |
def gcd(a, b): | |
if b == 0: | |
return a | |
else: | |
return gcd(b, a%b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment