-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp15_Frac.py
78 lines (61 loc) · 2.12 KB
/
p15_Frac.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
"""
coding=utf-8
@Author : Wu Wentong
@Time : 2021/2/23 8:19 下午
@Site :
@File : p15_Frac.py
@Software: PyCharm
"""
class Frac:
def __init__(self, a, b):
"""
:param a: a表示分子
:param b: b表示分母
"""
m = gcd(a, b) # gcd最大公约数函数
self.a = a // m
self.b = b // m
def __repr__(self): # 定义打印函数,若打印都需要重定义__repr__
return "{}/{}".format(self.a, self.b)
def __add__(self, other):
other = to_frac(other) # 将非分数转化为分数
return Frac(self.a * other.b + self.b * other.a, self.b * other.b)
def __radd__(self, other):
return self.__add__(other) # 右边相加和左边相加结果一致,所以直接调用__add__即可
def __sub__(self, other):
return Frac(self.a * other.b - self.b * other.a, self.b * other.b)
def __rsub__(self, other):
other = to_frac(other)
return Frac(other.a * self.b - other.b * self.a, self.b * other.b)
def __neg__(self):
return Frac(- self.a, self.b)
def __mul__(self, other):
other = to_frac(other)
return Frac(other.a * self.a, other.b * self.b)
def __truediv__(self, other):
other = to_frac(other)
return Frac(other.a * self.b, other.b * self.a)
def to_frac(value):
if isinstance(value, Frac): # 如果本身就是Frac分数就返回本身
return value
if type(value) == int: # 如果它本身是整数,返回分子为对应整数,分母为1即可
return Frac(value, 1)
raise Exception('expect an integer, but found {}'.format(value))
def gcd(x1, x2): # 辗转相除法找最大公约数
a = min(x1, x2)
b = max(x1, x2)
while a != 0:
t = b % a
b = a
a = t
return b
if __name__ == "__main__":
f1 = Frac(-3, 4)
f2 = Frac(2, 3)
print(f1, "+", f2, "=", f1 + f2)
print(f1, "-", f2, "=", f1 - f2)
print("-", f1, "=", -f1)
print(f1, "+", 3, f1 + 3)
print(3, "+", f1, "=", 3 + f1)
print(f1, "*", f2, "=", f1 * f2)
print(f1, "/", f2, "=", f1 / f2)