gpt4 book ai didi

python - 我自己制作分数课

转载 作者:行者123 更新时间:2023-12-01 02:03:24 24 4
gpt4 key购买 nike

我正在尝试创建我自己的“分数类”。几乎所有代码都可以正常工作,但在 / , > , < ,这些都不起作用。我不知道我的代码有什么问题。

def gcd(m, n):
while m%n != 0:
m, n = n, m%n
return n

class Fraction:
'''Fractional class'''

def __init__(self, num, denom):
self.num = num
self.denom = denom

def __str__(self):
return str(self.num)+'/'+str(self.denom)

def __add__(self, other):
new_num = self.num * other.denom + other.num * self.denom
new_denom = self.denom * other.denom
common = gcd(new_num, new_denom)
return Fraction(new_num//common, new_denom//common)

def __sub__(self, other):
new_num = self.num * other.denom - other.num * self.denom
new_denom = self.denom * other.denom
common = gcd(new_num, new_denom)
return Fraction(new_num//common, new_denom//common)

def __mul__(self, other):
new_num = self.num * other.num
new_denom = self.denom * other.denom
common = gcd(new_num, new_denom)
return Fraction(new_num//common, new_denom//common)

def __div__(self, other):
new_num = self.num * other.denom
new_denom = self.denom * other.num
common = gcd(new_num, new_denom)
return Fraction(new_num//common, new_denom//common)


def __equal__(self, other):
return (self.num * other.denom) == (other.num * self.denom)

def __big__(self, other):
return str(self.num * other.denom) > str(other.num * self.denom)

def __small__(self, other):
return self.num * other.denom < other.num * self.denom



if __name__ == "__main__":

f1 = Fraction(1,4)
f2 = Fraction(1,2)
print(f1+f2)
print(f1 - f2)
print(f1 * f2)
print(f1 / f2) #not working

print(f1 == f2)
print(f1 > f2) #not working
print(f1 < f2) #not working

我得到以下输出:

3/4
-1/4
1/8
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-50-50cad0951bd1> in <module>()
57 print(f1 - f2)
58 print(f1 * f2)
---> 59 print(f1 / f2) #not working
60
61 print(f1 == f2)

TypeError: unsupported operand type(s) for /: 'Fraction' and 'Fraction'

我定义__div__吗?正确吗?

最佳答案

Python 3.x 使用 __truediv____floordiv____div__ 用于 python 2.x。

要进行比较,您需要定义 __lt____gt____ge____le__

关于python - 我自己制作分数课,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49340174/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com