-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathmagic-methods-2.py
93 lines (75 loc) · 1.99 KB
/
magic-methods-2.py
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
86
87
88
89
90
91
92
# Copyright (C) Deepali Srivastava - All Rights Reserved
# This code is part of Python course available on CourseGalaxy.com
class Fraction:
def __init__(self,nr,dr=1):
self.nr = nr
self.dr = dr
if self.dr < 0:
self.nr *= -1
self.dr *= -1
self._reduce()
def show(self):
print(f'{self.nr}/{self.dr}')
def __add__(self,other):
if isinstance(other,int):
other = Fraction(other)
f = Fraction(self.nr * other.dr + other.nr * self.dr, self.dr * other.dr)
f._reduce()
return f
def multiply(self,other):
if isinstance(other,int):
other = Fraction(other)
f = Fraction(self.nr * other.nr , self.dr * other.dr)
f._reduce()
return f
def __eq__(self,other):
return (self.nr * other.dr) == (self.dr * other.nr)
def __lt__(self,other):
return (self.nr * other.dr) < (self.dr * other.nr)
def __le__(self,other):
return (self.nr * other.dr) <= (self.dr * other.nr)
def __str__(self):
return f'{self.nr}/{self.dr}'
def __repr__(self):
return f'Fraction({self.nr},{self.dr})'
def _reduce(self):
h = Fraction.hcf(self.nr, self.dr)
if h == 0:
return
self.nr //= h
self.dr //= h
@staticmethod
def hcf(x,y):
x=abs(x)
y=abs(y)
smaller = y if x>y else x
s = smaller
while s>0:
if x%s==0 and y%s==0:
break
s-=1
return s
def __radd__(self,other):
return self.__add__(other)
f1 = Fraction(2,3)
f2 = Fraction(2,3)
f3 = Fraction(4,6)
print(f1 == f2)
print(f1 == f3 )
print(f1 != f2)
f1 = Fraction(2,3)
f2 = Fraction(2,3)
f3 = Fraction(1,5)
print(f1 < f2)
print(f1 <= f2)
print(f1 < f3)
print(f3 < f1)
print(str(f1))
print(f1)
f1 = Fraction(3,4)
f2 = Fraction(4,5)
f3 = Fraction(1,5)
L = [f1,f2,f3]
print(L)
f2 = f1 + 3
f2 = 3 + f1