Forezz

ООП ДЗ 2

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