Sofya_Soloveva_

Untitled

Jul 23rd, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. from functools import total_ordering
  2. @total_ordering
  3. class Fraction:
  4.    
  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 __radd__(self,other):
  25.         return self,other
  26.    
  27.     def __float__(self):
  28.         return self.numerator/self.denominator
  29.            
  30.     def __str__(self):
  31.         self._reduce()
  32.         return str(self.numerator) + '/'+ str(self.denominator)
  33.    
  34.     def __eq__(self,other):
  35.         self._reduce()
  36.         other._reduce()
  37.         return self.numerator == other.numerator and self.denominator == other.denominator
  38.    
  39.     def __lt__(self,other):
  40.         self._reduce()
  41.         other._reduce()        
  42.         return self.numerator * other.denominator - self.denominator * other.numerator < 0
  43.    
  44.     def __neg__(self):
  45.         return  Fraction(-self.numerator,self.denominator)
  46.    
  47.     def __sub__(self,other):
  48.         return Fraction(self.numerator * other.denominator - self. denominator * other.numerator, self.denominator * other.denominator)
  49.    
  50.     def __mul__(self,other):
  51.         return Fraction(self.numerator * other.numerator, self.denominator * other.denominator)
  52.    
  53.    
  54. fraction_result = Fraction(1,4)
  55. print(fraction_result)
Advertisement
Add Comment
Please, Sign In to add comment