class Fraction:
"""Class for performing fraction arithmetic.
Each Fraction has two attributes: a numerator, n and a deconominator, d.
Both must be integer and the deonominator cannot be zero."""
def __init__(self,n,d):
"""Performs error checking and standardises to ensure denominator is
positive"""
if type(n)!=int or type(d)!=int:
raise TypeError("n and d must be integers")
if d==0:
raise ValueError("d must be positive")
elif d<0:
self.n = -n
self.d = -d
else:
self.n = n
self.d = d
def __str__(self):
"""Gives string representation of Fraction (so we can use print)"""
return(str(self.n) + "/" + str(self.d))
def __add__(self, otherFrac):
"""Produces new Fraction for the sum of two Fractions"""
newN = self.n*otherFrac.d + self.d*otherFrac.n
newD = self.d*otherFrac.d
newFrac = Fraction(newN, newD)
return(newFrac)
def __sub__(self, otherFrac):
"""Produces new Fraction for the difference between two Fractions"""
newN = self.n*otherFrac.d - self.d*otherFrac.n
newD = self.d*otherFrac.d
newFrac = Fraction(newN, newD)
return(newFrac)
def __mul__(self, otherFrac):
"""Produces new Fraction for the product of two Fractions"""
newN = self.n*otherFrac.n
newD = self.d*otherFrac.d
newFrac = Fraction(newN, newD)
return(newFrac)
def __truediv__(self, otherFrac):
"""Produces new Fraction for the quotient of two Fractions"""
newN = self.n*otherFrac.d
newD = self.d*otherFrac.n
newFrac = Fraction(newN, newD)
return(newFrac)如上面所示,我如何打印?
Fraction(1,3) == Fraction(2,6)例如:
Fraction(1,2) + Fraction(1,3)
Fraction(1,2) - Fraction(1,3)
Fraction(1,2) * Fraction(1,3)
Fraction(1,2) / Fraction(1,3)他们每次都是计算的工作。当我试图打印分数(1,3) ==分数(2,6)时,结果是False。我怎么能让它计算成True
我怎样才能不使用import fraction就能做到这一点。
发布于 2017-05-16 13:58:25
试试这个:
def __eq__(self, other):
return self.n*other.d == self.d*other.n正如注释中所指出的,没有必要实现__ne__。
编辑:,如对此答案的注释中所要求的,这里是简化分数的方法。
分数的简化意味着将这两个数除以最大公因子。正如在这里中发布的那样,代码相当简单
# return the simplified version of a fraction
def simplified(self):
# calculate the greatest common divisor
a = self.n
b = self.d
while b:
a, b = b, a%b
# a is the gcd
return Fraction(self.n/a, self.d/a)希望能帮上忙。
发布于 2017-05-16 13:55:13
数据模型将__eq__指定为实现==检查的方法。
__eq__的一个非常简单的实现是:
def __eq__(self, other):
return self.n == other.n and self.d == other.d它适用于Fraction(1, 2) == Fraction(1, 2),但不适用于Fraction(1, 2) == Fraction(2, 4)。
您需要修改__eq__方法的内容,以便它甚至允许比较倍数。
发布于 2017-05-16 13:48:33
在python中,要获得==操作符的自定义行为,必须为方法__eq__提供一个实现。如果您不覆盖它,默认的行为是检查对象是否真的是同一个对象,在本例中不是这样。
https://stackoverflow.com/questions/44003263
复制相似问题