Advertisement
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,denominator):
- numerator / denominator
- self.numerator = numerator
- self.denominator = denominator
- def _reduce(self):
- a = self.numerator
- b = self.denominator
- while b != 0:
- a,b = b,a%b
- self.numerator //= a
- self.denominator //= a
- return self
- def __neg__(self): # un-
- return (-self.numerator, self.denominator)
- def __add__(self,other): # +
- if type(other) == int:
- other = Fraction(other,1)
- return Fraction((self.numerator * other.denominator) + (other.numerator * self.denominator), self.denominator * other.denominator)
- def __sub__(self,other): # -
- return Fraction((self.numerator * other.denominator) - (other.numerator * self.denominator), self.denominator * other.denominator)
- def __mul__(self, other): # *
- return Fraction(self.numerator * other.numerator, self.denominator * other.denominator)
- def __truediv__(self, other): # /
- return Fraction((self.numerator * other.denominator), (self.denominator * other.numerator))
- def __radd__(self,other):
- return self + other
- def __float__(self):
- return self.numerator / self.denominator
- def __str__(self):
- d = self._reduce()
- if self.numerator == 0:
- return str(0)
- elif self.numerator % self.denominator == 0:
- return str(self.numerator // self.denominator)
- elif self.numerator > self.denominator:
- return str(self.numerator // self.denominator) + " " + str(self.numerator % self.denominator) + "/" + str(self.denominator)
- else:
- return str(self.numerator) + "/" + str(self.denominator)
- def __eq__(self, other): # ==
- other._reduce()
- self._reduce()
- return self.numerator == other.numerator and self.denominator == other.denominator
- def __lt__(self,other): # <
- return self.numerator * other.denominator - self.denominator * other.numerator < 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement