为嵌入式类函数指定运算符

2024-10-08 18:30:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的python入门课做家庭作业。 目标是定义要使用的函数*/+-<&燃气轮机<;=>;=具有类调用的运算符。这个特殊的程序采用3个参数self, inches, numerator, denominator,并将分母存储为64的因子(如果可以简化的话)

调用RulerUnit(2, 1, 4)将返回"2 1/4"

我正在处理乘法部分,当inches等于0时遇到了问题

inches == 0还是inches is None

此外,无论情况如何,当我执行以下断言时: assert(str(RulerUnit(2, 3, 4) * RulerUnit(0, 1, 2)) == "1 3/8")

一个AssertionError就是我的代码

print((RulerUnit(2, 3, 4) * RulerUnit(0, 1, 2)))

打印2 3/8

代码:

def __mul__ (self, other):

    if self.inches == 0 and other.inches == 0:
        newnum = self.num * other.num
        finaldenom = self.denom * other.denom
        finalnum = newnum % 64
        finalinches = newnum // finaldenom
        return RulerUnit(finalinches, finalnum, finaldenom)

    elif self.inches == 0 and other.inches != 0:
        newnum1 = (self.inches * self.denom) + self.num
        finaldenom = self.denom * other.denom
        finalnum = (newnum1 * other.num) % 64
        finalinches = (newnum1 * other.num) // finaldenom
        return RulerUnit(finalinches, finalnum, finaldenom)

    elif self.inches!= 0 and other.inches == 0:
        newnum1 = (self.inches * self.denom) + self.num
        finaldenom = self.denom * other.denom
        finalnum = (newnum1 * other.num) % 64
        finalinches = (newnum1 * other.num) // finaldenom
        return RulerUnit(finalinches, finalnum, finaldenom)

    elif self.inches != 0 and other.inches != 0:
        newnum1 = (self.inches * self.denom) + self.num
        newnum2 = (other.inches * other.denom) + other.num
        finaldenom = (self.denom * other.denom) % 64
        finalnum = (newnum1 * newnum2) % 64
        finalinches = (newnum1 * newnum2) // finaldenom
        return RulerUnit(finalinches, finalnum, finaldenom)

Tags: andselfreturnnumotherelifinchesnewnum
2条回答

您应该规范化存储值的方式。2 3/8实际上是19/8。一旦你这么做了,数学就变得微不足道了。输入和输出使用混合数,但内部使用纯分数

class Ruler:
    def __init__(self, inches, n, d):
        self.n = inches*d + n
        self.d = d

    def __str__(self):
        inches, n = divmod(self.n, d)
        return "{} {}/{}".format(inches, n, self.d)

    def __mul__(self, other):
        return Ruler(0, self.n * other.n, self.d * other.d)

当某个值的inches部分为零时,不需要特殊情况。你只需要在计算中使用零,它应该是正确的:

def __mul__(self, other):
    num = (self.inches * self.denom + self.num) * (other.inches * other.denom + other.num)
    denom = self.denom * other.denom
    inches, num = divmod(num, denom)
    return RulerUnit(inches, num, denom)

相关问题 更多 >

    热门问题