Skip to content

Instantly share code, notes, and snippets.

@cyyeh
Created March 16, 2017 14:34
Show Gist options
  • Save cyyeh/af717aedc9f077805d89f1fff74bffaa to your computer and use it in GitHub Desktop.
Save cyyeh/af717aedc9f077805d89f1fff74bffaa to your computer and use it in GitHub Desktop.
# Euclid's algoithm
def gcd(m, n):
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
return n
# ADT for number presenting in fraction form
class Fraction:
# constructor
def __init__(self, top, bottom):
if not(isinstance(top, int)) or not(isinstance(bottom, int)):
raise RuntimeError("Both numerator and denominator should be integers.")
if bottom == 0:
raise RuntimeError("Denominator can't be 0.")
if bottom < 0:
bottom *= -1
top *= -1
common = gcd(top, bottom)
self.num = top//common
self.den = bottom//common
# override print()
def __str__(self):
return str(self.num)+"/"+str(self.den)
# get numerator
def getNum(self):
return self.num
# get denominator
def getDen(self):
return self.den
# add
def __add__(self, otherfraction):
newnum = self.num * otherfraction.den + self.den * otherfraction.num
newden = self.den * otherfraction.den
return Fraction(newnum, newden)
# subtraction
def __sub__(self, otherfraction):
newnum = self.num * otherfraction.den - self.den * otherfraction.num
newden = self.den * otherfraction.den
return Fraction(newnum, newden)
# multiplication
def __mul__(self, otherfraction):
newnum = self.num * otherfraction.num
newden = self.den * otherfraction.den
return Fraction(newnum, newden)
# division
def __truediv__(self, otherfraction):
newnum = self.num * otherfraction.den
newden = self.den * otherfraction.num
return Fraction(newnum, newden)
# check if equal
def __eq__(self, otherfraction):
firstnum = self.num * otherfraction.den
secondnum = otherfraction.num * self.den
return firstnum == secondnum
# check if greater than
def __gt__(self, otherfraction):
return (self - otherfraction).getNum() > 0
# check if greater than or equal
def __ge__(self, otherfraction):
return (self - otherfraction).getNum() >= 0
# check if less than
def __lt__(self, otherfraction):
return (self - otherfraction).getNum() < 0
# check if less than or equal
def __le__(self, otherfraction):
return (self - otherfraction).getNum() <= 0
# check if not equal
def __ne__(self, otherfraction):
firstnum = self.num * otherfraction.den
secondnum = otherfraction.num * self.den
return firstnum != secondnum
def main():
x = Fraction(1, 0)
y = Fraction(1, 2)
print("Numirator of ", x, " => ", x.getNum())
print("Denominator of ", x, " => ", x.getDen())
print(x, " + ", y, " => ", x + y)
print(x, " - ", y, " => ", x - y)
print(x, " * ", y, " => ", x * y)
print(x, " == ", y, " => ", x == y)
print(x, " > ", y, " => ", x > y)
print(x, " >= ", y, " => ", x >= y)
print(x, " < ", y, " => ", x < y)
print(x, " <= ", y, " => ", x <= y)
print(x, " != ", y, " => ", x != y)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment