Advertisement
Guest User

Untitled

a guest
Aug 25th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. from functools import total_ordering
  2. @total_ordering
  3. class Fraction:
  4.     def __init__(self,numerator,denominator):
  5.         numerator / denominator
  6.         self.numerator = numerator
  7.         self.denominator = denominator
  8.     def _reduce(self):
  9.         a = self.numerator
  10.         b = self.denominator
  11.         while b != 0:
  12.             a,b = b,a%b
  13.         self.numerator //= a
  14.         self.denominator //= a
  15.         return self
  16.     def __neg__(self): # un-
  17.         return (-self.numerator, self.denominator)
  18.     def __add__(self,other): # +
  19.         if type(other) == int:
  20.             other = Fraction(other,1)
  21.         return Fraction((self.numerator * other.denominator) + (other.numerator * self.denominator), self.denominator * other.denominator)
  22.     def __sub__(self,other): # -
  23.         return Fraction((self.numerator * other.denominator) - (other.numerator * self.denominator), self.denominator * other.denominator)
  24.     def __mul__(self, other): # *
  25.         return Fraction(self.numerator * other.numerator, self.denominator * other.denominator)
  26.     def __truediv__(self, other): # /
  27.         return Fraction((self.numerator * other.denominator), (self.denominator * other.numerator))
  28.     def __radd__(self,other):
  29.         return self + other
  30.     def __float__(self):
  31.         return self.numerator / self.denominator
  32.     def __str__(self):
  33.         d = self._reduce()
  34.         if self.numerator == 0:
  35.             return str(0)
  36.         elif self.numerator % self.denominator == 0:
  37.             return str(self.numerator // self.denominator)
  38.         elif self.numerator > self.denominator:
  39.             return str(self.numerator // self.denominator) + " " + str(self.numerator % self.denominator) + "/" + str(self.denominator)        
  40.         else:
  41.             return str(self.numerator) + "/" + str(self.denominator)
  42.     def __eq__(self, other): # ==
  43.         other._reduce()
  44.         self._reduce()
  45.         return self.numerator == other.numerator and self.denominator == other.denominator
  46.     def __lt__(self,other): # <
  47.         return self.numerator * other.denominator - self.denominator * other.numerator < 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement