Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.11 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 + self.denominator * other.numerator, self.denominator * other.denominator)
  23.    
  24.     def __sub__(self, other): #-
  25.         if type(other) == int:
  26.             other = Fraction(other,1)
  27.         return Fraction(self.numerator * other.denominator - self.denominator * other.numerator, self.denominator * other.denominator)
  28.    
  29.     def __mul__(self,other):  #*
  30.         if type(other) == int:
  31.             other = Fraction(other,1)
  32.         return Fraction(self.numerator * other.numerator, self.denominator * other.denominator)
  33.    
  34.     def __float__(self):
  35.         return self.numerator / self.denominator
  36.    
  37.     def __radd__(self, other):
  38.         return self + other
  39.    
  40.     def __str__(self):
  41.         self._reduce()
  42.         if self.numerator == 0:
  43.             return str(0)
  44.         elif self.numerator // self.denominator == 0:
  45.             return  str(self.numerator) + '/' + str(self.denominator)
  46.         elif self.numerator % self.denominator == 0:
  47.             return str(self.numerator // self.denominator)
  48.         else:
  49.             return str(self.numerator // self.denominator) + ' ' + str(self.numerator % self.denominator) + '/' + str(self.denominator)
  50.    
  51.     def __eq__(self, other):  #==
  52.         self._reduce()
  53.         other._reduce()
  54.         return self.numerator == other.numerator and self.denominator == other.denominator
  55.    
  56.     def __lt__(self, other): #<
  57.         return self.numerator * other.denominator - self.denominator * other.numerator < 0
  58.    
  59. f = Fraction(35,21)
  60. print(f)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement