Skip to content

Instantly share code, notes, and snippets.

@schmit
Last active August 29, 2015 14:21
Show Gist options
  • Save schmit/875840d1a231526b572e to your computer and use it in GitHub Desktop.
Save schmit/875840d1a231526b572e to your computer and use it in GitHub Desktop.
cme193 demo: Rational class
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