Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from functools import total_ordering
- @total_ordering
- class Fraction:
- def __init__(self, numerator, demoninator):
- numerator / demoninator
- self.numerator = numerator
- self.demoninator = demoninator
- def _reduce(self): #NOD
- a = self.numerator
- b = self.demoninator
- while b != 0:
- a, b = b, a%b
- self.numerator //= a
- self.demoninator //= a
- return self
- def __str__(self):
- self._reduce()
- if abs(self.numerator) >= abs(self.demoninator):
- if self.numerator % self.demoninator != 0:
- return str(self.numerator // self.demoninator) + " " + str(self.numerator % self.demoninator) + '/' + str(self.demoninator)
- if self.numerator % self.demoninator == 0:
- return str(self.numerator // self.demoninator)
- elif self.numerator == 0:
- return str(0)
- else:
- return str(self.numerator) + "/" + str(self.demoninator)
- def __add__(self, other):
- if type(other) == int:
- other = Fraction(other, 1)
- return Fraction(self.numerator * other.demoninator + self.demoninator * other.numerator, self.demoninator * other.demoninator)
- def __radd__(self, other):
- return self + other
- def __eq__(self, other):
- self._reduce()
- other._reduce()
- return self.numerator == other.numerator and self.demoninator == other.demoninator
- def __it__(self, other):
- self._reduce()
- other._reduce()
- return self.numerator * other.demoninator - other.numerator * self.demoninator < 0
- def __float__(self):
- return self.numerator / self.demoninator
- def __floordiv__(self, other):
- return Fraction(self.numerator * other.demoninator, self.demoninator * other.numerator)
- def __mul__(self, other):
- return Fraction(self.numerator * other.numerator, self.demoninator * other.demoninator)
- def __sub__(self, other):
- if type(other) == int:
- other = Fraction(other, 1)
- if type(self) == int:
- self = Fraction(self, 1)
- return Fraction(self.numerator * other.demoninator - self.demoninator * other.numerator, self.demoninator * other.demoninator)
- def __neg__(self):
- return Fraction(-self.numerator, self.demoninator)
- f = Fraction(4, 2)
- d = Fraction(2, 5)
Advertisement
Add Comment
Please, Sign In to add comment