-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathmagic-methods-1.py
62 lines (48 loc) · 1.28 KB
/
magic-methods-1.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
# 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 _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
f1 = Fraction(2,3)
f2 = Fraction(3,4)
#f3 = f1+f2
##f3 = f1*f2
f3 = f1.add(f2)
f3.show()
f3 = f1.multiply(f2)