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 __add__(self, other):
- if type(other) == int:
- other = Fraction(other,1)
- return Fraction(self.numerator * other.denominator + self.denominator * other.numerator, self.denominator * other.denominator)
- def __sub__(self, other):
- if type(other) == int:
- other = Fraction(other,1)
- return Fraction(self.numerator * other.denominator - self.denominator * other.numerator, self.denominator * other.denominator)
- def __mul__(self, other):
- if type(other) == int:
- other = Fraction(other,1)
- return Fraction(self.numerator * other.numerator, self.denominator * other.denominator)
- def __neg__(self):
- self.numerator = -self.numerator
- return Fraction(self.numerator, self.denominator)
- def __float__(self):
- return self.numerator / self.denominator
- def __radd__(self, other):
- return self + other
- def __str__(self):
- self._reduce()
- return str(self.numerator) + "/" + str(self.denominator)
- def __eq__(self, other):
- self._reduce()
- other._reduce()
- return self.numerator == other.numerator and self.denominator == other.denominator
- def __lt__(self, other):
- self._reduce()
- other._reduce()
- return self.numerator * other.denominator - self.denominator * other.numerator < 0
- f=Fraction(10,-2)
- f = -f
- print(float(f))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement