Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. class Rational:
  2. def __init__(self, x, y):
  3. self.x = x
  4. self.y = y
  5. def get_numerator(self):
  6. return self.x
  7. def get_denominator(self):
  8. return self.y
  9. def to_float(self):
  10. return self.x/self.y
  11. def reciprocal(self):
  12. a=self.x
  13. b=self.y
  14. rec=Rational(b,a)
  15. return rec
  16. def reduce(self):
  17. list=[]
  18. for i in range(1, self.x+1):
  19. if self.x % i ==0 and self.y % i==0 :
  20. list.append(i)
  21. j = int(self.x / list[-1])
  22. k = int(self.y / list[-1])
  23. red = Rational(j, k)
  24. return red
  25.  
  26. def __add__(self, other):
  27. if isinstance(other, Rational):
  28. denom= self.y * other.y
  29. numer=self.x * other.y + self.y * other.x
  30. add3 = Rational(numer,denom)
  31. return add3
  32. if isinstance(other, float):
  33. return self.x/self.y+ other
  34. if isinstance(other, int):
  35. numer=other*self.y+self.x
  36. denom=self.y
  37. add3 = Rational(numer, denom)
  38. return add3
  39. else:
  40. return None
  41. def __mul__(self, other):
  42. if isinstance(other, Rational):
  43. num=self.x * other.x
  44. denom= self.y * other.y
  45. add3 = Rational(num, denom)
  46. return add3
  47. if isinstance(other, float):
  48. return self.x / self.y * other
  49. if isinstance(other, int):
  50. numer = other * self.x
  51. denom = self.y
  52. add3 = Rational(numer, denom)
  53. return add3
  54. else:
  55. return None
  56. def __truediv__(self, other):
  57. if isinstance(other, Rational):
  58. num=self.x * other.y
  59. denom= self.y * other.x
  60. add3 = Rational(num, denom)
  61. return add3
  62. if isinstance(other, float):
  63. return self.x / (self.y * other)
  64. if isinstance(other, int):
  65. numer = self.x
  66. denom = self.y*other
  67. add3 = Rational(numer, denom)
  68. return add3
  69. else:
  70. return None
  71. def __sub__(self, other):
  72. if isinstance(other, Rational):
  73. denom = self.y * other.y
  74. numer = self.x * other.y - self.y * other.x
  75. add3 = Rational(numer, denom)
  76. return add3
  77. if isinstance(other, float):
  78. return self.x / self.y - other
  79. if isinstance(other, int):
  80. numer =self.x-other * self.y
  81. denom = self.y
  82. add3 = Rational(numer, denom)
  83. return add3
  84. else:
  85. return None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement