forked from samiullahsaleem/cyberblock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rational Class
85 lines (79 loc) · 2.19 KB
/
Rational Class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from math import gcd
class Rational:
def __init__(self):
self.__p = 0
self.__q = 1
def set(self, p, q):
self.__p = p
if q == 0:
q = 1
self.__q = q
def __str__(self):
if self.__p>0 and self.__q<0:
self.__p=-self.__p
self.__q=-self.__q
return f'{str(self.__p)}/{str(self.__q)}'
elif self.__p<0 and self.__q<0:
self.__p=-self.__p
self.__q=-self.__q
return f'{str(self.__p)}/{str(self.__q)}'
else:
return f'{str(self.__p)}/{str(self.__q)}'
def __eq__(self, obj):
return self.__p == obj.__p and self.__q == obj.__q
def __sub__(self, obj):
new_object = Rational()
new_object.__q = self.__q * obj.__q
new_object.__p = (self.__p * obj.__q) - (self.__q * obj.__p)
return new_object
def __add__(self, obj):
new_object = Rational()
new_object.__q = self.__q * obj.__q
new_object.__p = (self.__p * obj.__q) + (self.__q * obj.__p)
return new_object
def __mul__(self, obj):
new_object = Rational()
new_object.__q = self.__q * obj.__q
new_object.__p = (self.__p * obj.__q) * (self.__q * obj.__p)
return new_object
def __gt__(self,obj):
if (self.__p / self.__q) > (obj.__p /obj.__q):
return True
else:
return False
def __lt__(self,obj):
if (self.__p / self.__q) < (obj.__p /obj.__q):
return True
else:
return False
def normalize(self):
d=gcd(self.__p,self.__q)
self.__p=int(self.__p / d)
self.__q=int(self.__q / d)
return self.__p , self.__q
def main():
r1 = Rational()
r2 = Rational()
r3 = Rational()
r1.set(36,12)
print(r1)
print(r1.normalize())
r2.set(21,7)
r3.set(9,3)
print(r2)
print(r2.normalize())
print(r3)
print(r3.normalize())
if r1 == r2:
print ('Both are equal')
if r1 == r3:
print ('Both are equal')
else:
print ('Both are different')
print(r1 > r2)
print(r1 > r3)
r4 = r1 - r3
r5=r1 * r3
print(r4)
print(r5)
main()