Advertisement
Guest User

Untitled

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