gpt4 book ai didi

python - 添加分数类 python

转载 作者:太空宇宙 更新时间:2023-11-04 10:46:57 24 4
gpt4 key购买 nike

我有一个类的这一部分,它接受一个整数和一个分数并将它们加在一起。

def __add__(self, g):
whole_add=self.whole_number + g.whole_number
numerator = (self.fraction.numerator * g.fraction.denominator ) + (g.fraction.numerator * self.fraction.denominator)
denominator = self.fraction.denominator * g.fraction.denominator
f=Fraction(numerator,denominator)
return '{} and {}'.format(whole_add,f)

fraction_1 = Fraction(3, 4)
fraction_2 = Fraction(2, 3)
mixed_num_1 = MixedNumber(2, fraction_1)
mixed_num_2 = MixedNumber(1, fraction_2)
print(mixed_num_1 + mixed_num_2)

结果是 3 和 17/12,当它应该是 4 和 5/12 时,我不确定该怎么做,我假设如果分数 >= 1。任何帮助都会很大赞赏

最佳答案

如果您使用 fractions library ,您可以对所有内容求和,然后取分数的 int() 部分:

def __add__(self, g):
summed = sum((self.whole_number, g.whole_number, self.fraction, g.fraction))
whole = int(summed)
remainder = summed - whole
return '{} and {}'.format(whole, remainder)

Fraction() 类为您实现了__add__,您可以对整数和Fraction() 对象求和,它的工作原理如下它应该。

使用常量的演示:

>>> from fractions import Fraction
>>> summed = sum((2, 1, Fraction(3, 4), Fraction(2, 3)))
>>> whole = int(summed)
>>> remainder = summed - whole
>>> '{} and {}'.format(whole, remainder)
'4 and 5/12'

一个鲜为人知但方便的事实是 Python 的 int() 类型同时具有 .numerator.denominator 属性,即fractions.Fraction() 类使用。如果您使用fractions 库,您可以自己使用它:

def __add__(self, g):
summed = 0
for v in (self.whole_number, g.whole_number, self.fraction, g.fraction):
summed = Fraction(summed.numerator * v.denominator +
v.numerator * summed.denominator,
summed.denominator * v.denominator)
whole = summed._numerator // summed._denominator
remainder = Fraction(summed.numerator * whole.denominator -
whole.numerator * summed.denominator,
summed.denominator * whole.denominator)
return '{} and {}'.format(whole, remainder)

关于python - 添加分数类 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16725345/

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