Python 以其他方式添加分数
我想添加两个分数类对象。 下面,我使用gcd(最大公因数)函数创建了一个分数类的方法 有没有其他方法可以不用gcd求两个分数的和? 有没有提到gcd是如何实施的Python 以其他方式添加分数,python,python-3.x,Python,Python 3.x,我想添加两个分数类对象。 下面,我使用gcd(最大公因数)函数创建了一个分数类的方法 有没有其他方法可以不用gcd求两个分数的和? 有没有提到gcd是如何实施的 import fractions class Fraction(object): def __init__(self, num, denom): self.num = num self.denom = denom def __str__(self): return f'
import fractions
class Fraction(object):
def __init__(self, num, denom):
self.num = num
self.denom = denom
def __str__(self):
return f'({self.num}/{self.denom})'
def gcd(self):
gcd = fractions.gcd(self.num, self.denom)
return gcd
def __add__(self, other):
gcd_self = self.gcd()
gcd_other = other.gcd()
top = (self.num//gcd_self) + (other.num//gcd_other)
bott = (self.denom//gcd_self) + (other.denom//gcd_other)
return Fraction(top, bott)
a = Fraction(1, 2)
b = a + a
print(b)
使用
gcd
并非绝对必要。你可以使用分数,而不用把分数简化成最简单的形式
def __add__(self, other):
return Fraction(self.num*other.denom + other.num*self.denom, self.denom*other.denom)
def __mul__(self, other):
return Fraction(self.num*other.num, self.denom*other.denom)
def __eq__(self, other):
return self.num*other.denom == self.denom*other.num
def __str__(self):
return f'{self.num}/{self.denom}'
# etc
这样,您实际上只需要在一个地方简化分数:\uuuu init\uuu
:
def __init__(self, num, denom):
# Computing f is optional, to avoid storing unnecessarily large
# integers and to simplify displays.
# The class will continue to work if you simply set f = 1.
f = fractions.gcd(num, denom)
self.num = num // f
self.denom = denom // f
注意这是内置的:@jornsharpe正在尝试理解实现。