Created
January 10, 2015 17:30
-
-
Save eirenik0/e953a868a9ea5625dc21 to your computer and use it in GitHub Desktop.
fractions for Problem Solving with Algorithms and Data Structures
This file contains hidden or 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
import unittest | |
def gcd(m, n): | |
while m % n != 0: | |
oldm = m | |
oldn = n | |
m = oldn | |
n = oldm % oldn | |
return n | |
class Fraction: | |
def __init__(self, top, bottom): | |
self.num = top | |
self.den = bottom | |
def __str__(self): | |
return str(self.num) + "/" + str(self.den) | |
def show(self): | |
print(self.num, "/", self.den) | |
def __add__(self, otherfraction): | |
newnum = self.num * otherfraction.den + \ | |
self.den * otherfraction.num | |
newden = self.den * otherfraction.den | |
common = gcd(newnum, newden) | |
return Fraction(newnum // common, newden // common) | |
def __truediv__(self, otherfraction): | |
firstmul = self.num * otherfraction.den | |
secondmul = self.den * otherfraction.num | |
return Fraction(firstmul, secondmul) | |
def __mul__(self, otherfraction): | |
firstmul = self.num * otherfraction.num | |
secondmul = self.den * otherfraction.den | |
return Fraction(firstmul, secondmul) | |
def __sub__(self, otherfraction): | |
newnum = self.num * otherfraction.den - \ | |
self.den * otherfraction.num | |
newden = self.den * otherfraction.den | |
common = gcd(newnum, newden) | |
return Fraction(newnum // common, newden // common) | |
def __eq__(self, other): | |
firstnum = self.num * other.den | |
secondnum = other.num * self.den | |
return firstnum == secondnum | |
def __gt__(self, other): | |
'self > otherfraction' | |
firstnum = self.num * other.den | |
secondnum = other.num * self.den | |
return firstnum > secondnum | |
def __lt__(self, other): | |
'self < otherfraction' | |
firstnum = self.num * other.den | |
secondnum = other.num * self.den | |
return firstnum < secondnum | |
class TestFractionFunction(unittest.TestCase): | |
def setUp(self): | |
self.x = Fraction(1, 2) | |
self.y = Fraction(2, 3) | |
def test_add(self): | |
self.assertEqual(self.x + self.y, Fraction(7,6)) | |
def test_sub(self): | |
self.assertEqual(self.x - self.y, Fraction(-1,6)) | |
def test_mul(self): | |
self.assertEqual(self.x * self.y, Fraction(1,3)) | |
def test_div(self): | |
self.assertEqual(self.x / self.y, Fraction(3,4)) | |
def test_eq(self): | |
self.assertEqual(self.x == self.y, False) | |
def test_gt(self): | |
self.assertEqual(self.x > self.y, False) | |
def test_lt(self): | |
self.assertEqual(self.x < self.y, True) | |
if __name__ == '__main__': | |
unittest.main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment