Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Rational:
- def __init__(self, x, y):
- self.x = x
- self.y = y
- def get_numerator(self):
- return self.x
- def get_denominator(self):
- return self.y
- def to_float(self):
- return self.x/self.y
- def reciprocal(self):
- a=self.x
- b=self.y
- rec=Rational(b,a)
- return rec
- def reduce(self):
- list=[]
- for i in range(1, self.x+1):
- if self.x % i ==0 and self.y % i==0 :
- list.append(i)
- j = int(self.x / list[-1])
- k = int(self.y / list[-1])
- red = Rational(j, k)
- return red
- def __add__(self, other):
- if isinstance(other, Rational):
- denom= self.y * other.y
- numer=self.x * other.y + self.y * other.x
- add3 = Rational(numer,denom)
- return add3
- if isinstance(other, float):
- return self.x/self.y+ other
- if isinstance(other, int):
- numer=other*self.y+self.x
- denom=self.y
- add3 = Rational(numer, denom)
- return add3
- else:
- return None
- def __mul__(self, other):
- if isinstance(other, Rational):
- num=self.x * other.x
- denom= self.y * other.y
- add3 = Rational(num, denom)
- return add3
- if isinstance(other, float):
- return self.x / self.y * other
- if isinstance(other, int):
- numer = other * self.x
- denom = self.y
- add3 = Rational(numer, denom)
- return add3
- else:
- return None
- def __truediv__(self, other):
- if isinstance(other, Rational):
- num=self.x * other.y
- denom= self.y * other.x
- add3 = Rational(num, denom)
- return add3
- if isinstance(other, float):
- return self.x / (self.y * other)
- if isinstance(other, int):
- numer = self.x
- denom = self.y*other
- add3 = Rational(numer, denom)
- return add3
- else:
- return None
- def __sub__(self, other):
- if isinstance(other, Rational):
- denom = self.y * other.y
- numer = self.x * other.y - self.y * other.x
- add3 = Rational(numer, denom)
- return add3
- if isinstance(other, float):
- return self.x / self.y - other
- if isinstance(other, int):
- numer =self.x-other * self.y
- denom = self.y
- add3 = Rational(numer, denom)
- return add3
- else:
- return None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement