Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中不正确的分数除法_Python_Python 3.x_Fractions - Fatal编程技术网

python中不正确的分数除法

python中不正确的分数除法,python,python-3.x,fractions,Python,Python 3.x,Fractions,我正在做一件事 其中一个练习是创建一个分数类,该类可以采用负分母,并且仍然正确地表示结果。但是,当我进行除法时,仍然得到负输出: class Fraction: def __init__(self, num, denom): if isinstance(num, int) or isinstance(denom, int): common = gcd(num, abs(denom)) self._num = num//com

我正在做一件事

其中一个练习是创建一个分数类,该类可以采用负分母,并且仍然正确地表示结果。但是,当我进行除法时,仍然得到负输出:

class Fraction:
    def __init__(self, num, denom):
        if isinstance(num, int) or isinstance(denom, int):
            common = gcd(num, abs(denom))
            self._num = num//common
            self._denom = abs(denom)//common
        else:
            raise TypeError

    def __str__(self):
        return "%d / %d" % (self._num, self._denom)

    def __mul__(self, other):
        denum = self._num * other._num
        div = self._denom * other._denom
        return Fraction(denum, div)

    def __truediv__(self, other):
        temp_fraction = Fraction(other._denom, other._num)
        return self.__mul__(temp_fraction)

def gcd(a, b):
    while(b):
        a, b = b, a%b
    return a

if __name__ == '__main__':
    print(Fraction(-4, -5) / Fraction(-1, -2)) 
    print(Fraction(-4, 5) / Fraction(-1, 2))
    # Both output -8 / 5, should be 8 / 5
有人能告诉我我做错了什么吗

编辑我已经更正了代码,并在doctest中重写了一些错误的断言。现在所有考试都通过了

完整代码:

from fractions import gcd

class Fraction:
    """
    Checking if instantiating a fraction works
    >>> print(Fraction(1, 2))
    1 / 2
    >>> print(Fraction(-1, 2))
    -1 / 2
    >>> print(Fraction('Foo', 'Bar'))
    Traceback (most recent call last):
    TypeError

    Adding a fraction to another fraction
    >>> print(Fraction(1, 2) + Fraction(1, 4))
    3 / 4
    >>> print(Fraction(-1, 2) + Fraction(2, 2))
    1 / 2
    >>> print(Fraction(-1, 5) + Fraction(-1, 5))
    -2 / 5
    >>> print(Fraction(-1, -5) + Fraction(-1, -5))
    2 / 5

    Substracting a fraction from another
    >>> print(Fraction(3, 4) - Fraction(1, 4))
    1 / 2
    >>> print(Fraction(-1, 2) - Fraction(1, 4))
    -3 / 4
    >>> print(Fraction(-2, 10) - Fraction(-1, 10))
    -1 / 10
    >>> print(Fraction(-2, -10) - Fraction(-1, -10))
    1 / 10

    Multiplying 2 fractions
    >>> print(Fraction(1, 5) * Fraction(1, 2))
    1 / 10
    >>> print(Fraction(-1, 2) * Fraction(1, 4))
    -1 / 8
    >>> print(Fraction(-1, 2) * Fraction(-1, 8))
    1 / 16
    >>> print(Fraction(-1, -2) * Fraction(-1, -8))
    1 / 16

    Dividing 2 fractions
    >>> print(Fraction(1, 4) / Fraction(1, 2))
    1 / 2
    >>> print(Fraction(-1, 2) / Fraction(1, 15))
    -15 / 2
    >>> print(Fraction(-4, 5) / Fraction(-1, 2))
    8 / 5
    >>> print(Fraction(-4, -5) / Fraction(-1, -2))
    8 / 5

    Equality between fractions
    >>> print(Fraction(1, 2) == Fraction(2, 4))
    True
    >>> print(Fraction(1, 2) == Fraction(1, 3))
    False
    >>> print(Fraction(-2, 4) == Fraction(-1, 2))
    True
    >>> print(Fraction(-2, -4) == Fraction(-1, -2))
    True

    Non-equality between fractions
    >>> print(Fraction(1, 2) != Fraction(64, 128))
    False
    >>> print(Fraction(1, 4) != Fraction(999, 4000))
    True
    >>> print(Fraction(-3, 4) != Fraction(-3, 5))
    True
    >>> print(Fraction(-3, -4) != Fraction(-3, -5))
    True

    Larger size difference between fractions
    >>> print(Fraction(1, 2) > Fraction(857, 1713))
    False
    >>> print(Fraction(1, 2) > Fraction(857, 1715))
    True
    >>> print(Fraction(1, 338) >= Fraction(2, 676))
    True
    >>> print(Fraction(-2, 5) > Fraction(-1, 5))
    False
    >>> print(Fraction(-2, -5) > Fraction(-1, -5))
    True

    Smaller size difference between fractions
    >>> print(Fraction(1, 2) < Fraction(857, 1713))
    True
    >>> print(Fraction(1, 2) < Fraction(857, 1715))
    False
    >>> print(Fraction(1, 338) <= Fraction(2, 676))
    True
    >>> print(Fraction(-3, 7) < Fraction(-6, 7))
    False
    >>> print(Fraction(-3, -7) < Fraction(-6, -7))
    True
    """
    def __init__(self, num, denom):
        if isinstance(num, int) and isinstance(denom, int):
            common = gcd(num, denom)
            self._num = num//common
            self._denom = denom//common
        else:
            raise TypeError

    def __str__(self):
        return "%d / %d" % (self._num, self._denom)

    def __add__(self, other):
        denum = (self._num * other.get_denom()) + (other.get_num() * self._denom)
        div = (self._denom * other.get_denom())
        return Fraction(denum, div)

    def __sub__(self, other):
        denum = (self._num * other.get_denom()) - (other.get_num() * self._denom)
        div = (self._denom * other.get_denom())
        return Fraction(denum, div)

    def __mul__(self, other):
        denum = self._num * other.get_num()
        div = self._denom * other.get_denom()
        return Fraction(denum, div)

    def __truediv__(self, other):
        temp_fraction = Fraction(other.get_denom(), other.get_num())
        return self.__mul__(temp_fraction)

    def eq_denum(self, other):
        first = self._num * other.get_denom()
        last = other.get_num() * self._denom
        return first, last

    def __eq__(self, other):
        first, last = self.eq_denum(other)
        return first == last

    def __ne__(self, other):
        first, last = self.eq_denum(other)
        return first != last

    def __gt__(self, other):
        first, last = self.eq_denum(other)
        return first > last

    def __ge__(self, other):
        first, last = self.eq_denum(other)
        return first >= last

    def __lt__(self, other):
        first, last = self.eq_denum(other)
        return first < last

    def __le__(self, other):
        first, last = self.eq_denum(other)
        return first <= last

    def get_num(self):
        return self._num

    def get_denom(self):
        return self._denom


if __name__ == '__main__':
    import doctest
    doctest.testmod()
从分数导入gcd
类别分数:
"""
检查实例化分数是否有效
>>>打印(分数(1,2))
1/2
>>>打印(分数(-1,2))
-1 / 2
>>>打印(分数('Foo','Bar'))
回溯(最近一次呼叫最后一次):
打字错误
把一个分数加到另一个分数上
>>>打印(分数(1,2)+分数(1,4))
3/4
>>>打印(分数(-1,2)+分数(2,2))
1/2
>>>打印(分数(-1,5)+分数(-1,5))
-2 / 5
>>>打印(分数(-1,-5)+分数(-1,-5))
2/5
从一个分数中减去另一个分数
>>>打印(分数(3,4)-分数(1,4))
1/2
>>>打印(分数(-1,2)-分数(1,4))
-3 / 4
>>>打印(分数(-2,10)-分数(-1,10))
-1 / 10
>>>打印(分数(-2,-10)-分数(-1,-10))
1/10
乘以2个分数
>>>打印(分数(1,5)*分数(1,2))
1/10
>>>打印(分数(-1,2)*分数(1,4))
-1 / 8
>>>打印(分数(-1,2)*分数(-1,8))
1/16
>>>打印(分数(-1,-2)*分数(-1,-8))
1/16
除以2个分数
>>>打印(分数(1,4)/分数(1,2))
1/2
>>>打印(分数(-1,2)/分数(1,15))
-15 / 2
>>>打印(分数(-4,5)/分数(-1,2))
8/5
>>>打印(分数(-4,-5)/分数(-1,-2))
8/5
分数相等
>>>打印(分数(1,2)=分数(2,4))
真的
>>>打印(分数(1,2)=分数(1,3))
假的
>>>打印(分数(-2,4)=分数(-1,2))
真的
>>>打印(分数(-2,-4)=分数(-1,-2))
真的
分数不相等
>>>打印(分数(1,2)!=分数(64128))
假的
>>>打印(分数(1,4)!=分数(999,4000))
真的
>>>打印(分数(-3,4)!=分数(-3,5))
真的
>>>打印(分数(-3,-4)!=分数(-3,-5))
真的
各部分之间的尺寸差异较大
>>>打印(分数(1,2)>分数(857113))
假的
>>>打印(分数(1,2)>分数(857115))
真的
>>>打印(分数(1338)>=分数(2676))
真的
>>>打印(分数(-2,5)>分数(-1,5))
假的
>>>打印(分数(-2,-5)>分数(-1,-5))
真的
各部分之间的尺寸差异较小
>>>印刷品(分数(1,2)<分数(857113))
真的
>>>印刷品(分数(1,2)<分数(857115))
假的
>>>打印(分数(1338)>>打印(分数(-3,7)<分数(-6,7))
假的
>>>打印(分数(-3,-7)<分数(-6,-7))
真的
"""
定义初始化(self、num、denom):
如果isinstance(num,int)和isinstance(denom,int):
公共=总分类(num,denom)
self.\u num=num//common
self.\u denom=denom//common
其他:
提高打字错误
定义(自我):
返回“%d/%d%”(self.\u num,self.\u denom)
定义添加(自身、其他):
denum=(self.\u num*other.get\u denom())+(other.get\u num()*self.\u denom)
div=(self.\u denom*other.get\u denom())
返回分数(denum,div)
定义(自身、其他):
denum=(self.\num*other.get\denom())-(other.get\num()*self.\denom)
div=(self.\u denom*other.get\u denom())
返回分数(denum,div)
定义多个(自身、其他):
denum=self.\num*other.get\u num()
div=self.\u denom*other.get\u denom()
返回分数(denum,div)
def _uTrueDiv__;(自身、其他):
temp\u分数=分数(other.get\u denom(),other.get\u num())
返回自整倍(温度分数)
定义均衡(自身、其他):
first=self.\u num*other.get\u denom()
last=other.get_num()*self.\u denom
先返回,后返回
定义(自身、其他):
第一,最后=自身均衡(其他)
返回第一个==最后一个
定义(自身、其他):
第一,最后=自身均衡(其他)
先回来
定义(自身、其他):
第一,最后=自身均衡(其他)
返回第一个>最后一个
定义(自身、其他):
第一,最后=自身均衡(其他)
返回第一个>=最后一个
定义(自身、其他):
第一,最后=自身均衡(其他)
先返回后返回
定义(自我、其他):
第一,最后=自身均衡(其他)

首先返回问题不在于除法,而在于如何使用
\uuuu init\uuuu
中的
gcd
函数

在创建分数时,似乎只需删除所有的
abs
。这样,如果
denom
为负数,则
gcd
将为负数,并获得所需的行为

if isinstance(num, int) and isinstance(denom, int):
    common = gcd(num, denom)
    self._num = num//common
    self._denom = denom//common
一些例子:

                            # with abs    # without abs
print(Fraction( 4,  6))     #  2/3           2/3
print(Fraction( 4, -6))     #  2/3          -2/3
print(Fraction(-4,  6))     # -2/3          -2/3
print(Fraction(-4, -6))     # -2/3           2/3

另外,请注意,两个数字都应该是整数,而不仅仅是其中一个(使用
)。

只需将\uuu str\uu更改为:

return "%d / %d" % (abs(self._num), abs(self._denom))

使用abs(number)来删除符号。我已经在对分母执行此操作,但在本例中,分子的问题是-x div-x不等于正数。如果要在参数之一不是整数时引发TypeError异常,请使用分数形式的If语句。\uu init应该使用and语句而不是or语句,因为您希望它们都是整数。但理想情况下,您确实不应该进行检查-Python更喜欢检查。这意味着,您不应该一直检查类型,而应该尝试执行您想要执行的操作,并在异常发生时处理异常。请查看第二段我链接到的Wikipedia条目的一部分。这不是