Advertisement
Guest User

Untitled

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