class Fraction: def __init__(self, num, den): if num < 1 and num > 0: self.num = num*100 self.den = 100 else: self.num = num self.den = den self._simplify() def __str__(self): return str(self.num) + "/" + str(self.den) def __radd__(self, other): return self.__add__(other) def __rsub__(self, other): return self.__sub__(other) def __rmul__(self, other): return self.__mul__(other) def __rdiv__(self, other): return self.__div__(other) def __add__(self, other): if isinstance(other, self.__class__): if self.den == other.den: return Fraction(self.num + other.num, self.den) else: num = self.num * other.den + other.num * self.den den = self.den * other.den return Fraction(num, den) elif isinstance(other, int): return Fraction(self.num + (other * self.den), self.den) def __sub__(self, other): if isinstance(other, self.__class__): if self.den == other.den: return Fraction(self.num - other.num, self.den) else: return Fraction(((self.num * other.den)-(other.num*self.den)),self.den * other.den ) elif isinstance(other, int): if other == 0: return Fraction(-self.num, self.den) else: return Fraction(self.num - (other * self.den), self.den) def __mul__(self, other): if isinstance(other, self.__class__): num = self.num * other.num den = self.den * other.den return Fraction(num, den) elif isinstance(other, int): return self * Fraction(other, 1) def __div__(self, other): if isinstance(other, self.__class__): num = self.num * other.den den = self.den * other.num return Fraction(num, den) elif isinstance(other, int): return self / Fraction(other, 1) def getNum(self): return self.num def getDen(self): return self.den def _gcf(self, first, second): while second: first, second = second, first % second return first def _simplify(self): if self.den == 0: return gcf = self._gcf(self.num, self.den) self.num = self.num / gcf self.den = self.den / gcf print Fraction(1, 3) + Fraction(1, 6) print Fraction(1, 3) - Fraction(1, 6) print Fraction(1, 3) * Fraction(1, 6) print Fraction(1, 3) / Fraction(1, 6) print Fraction(1,3) + 2 print Fraction(1,3) - 2 print Fraction(1,3) * 2 print Fraction(1,3) / 2 print 2 + Fraction(1,3) print 2 - Fraction(1,3) print 2 * Fraction(1,3) print 2 / Fraction(1,3) print Fraction(3, 12)