Algorithms and Data Structures学习———001.Fraction类
1、学习内容:
①学习重写Fraction类实现分数加法以及最大公约数算法
②理解浅相等与深相等
2、学习时间:2021.1.21
3、代码:
class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom
def show(self):
print(f"{self.num}/{self.den}")
def __str__(self):
"""重写str方法"""
return str(self.num) + "/" + str(self.den)
def __add__(self, otherfraction):
"""重写add方法"""
newnum = self.num * otherfraction.den + \
self.den * otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum//common, newden//common)
def __eq__(self, other):
"""重写eq方法"""
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum == secondnum
def gcd(m, n):
while m%n != 0:
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n