0

有理数を割るプログラムを書いていますが、分数を扱えるようにしたいです。1 を 1/3 で割りたいのですが、整数を処理するときにプログラムでエラーが発生します。整数をいくつかの異なる方法で有理数に変換しようとしましたが、何も機能しません。ヘルプやガイダンスをいただければ幸いです。

これは、コードの下部にある assert ステートメントからのフラグであるという、私が受け取り続けるエラーです。

トレースバック (最新の呼び出しが最後): ファイル "E:\Python\Rational number extension excercise.py"、47 行目、assert Rational(3) == 1 / r3、"除算テストに失敗しました。" TypeError: /: 'int' および 'Rational' のサポートされていないオペランド型

class Rational(object):
 """ Rational with numerator and denominator. Denominator
 parameter defaults to 1"""

 def __init__(self,numer,denom=1):  
     #test print('in constructor')
        self.numer = numer
        self.denom = denom

 def __truediv__(self,param):
    '''divide two rationals'''
    #test print('in truediv')
    if type(param) == int:  # convert ints to Rationals
        param = Rational(param)
    if type(param) == Rational:
        # find a common denominator (lcm)
        the_lcm = lcm(self.denom, param.numer)
        # adjust the param value
        lcm_numer = (the_lcm * param.numer)
        lcm_denom = (the_lcm * param.denom)
        true_param = int(lcm_denom / lcm_numer)
        #print(int(lcm_denom / lcm_numer))
        # multiply each by the lcm, then multiply
        numerator_sum = (the_lcm * self.numer/self.denom) * (true_param)
        #print(numerator_sum)
        #print(Rational(int(numerator_sum),the_lcm))
        return Rational(int(numerator_sum),the_lcm)
    else:
        print('wrong type')  # problem: some type we cannot handle
        raise(TypeError)

 def __rdiv__(self,param):
    '''divide two reversed rationals'''
    # mapping is correct: if "(1) / (x/x)", 1 maps (to 1/1)
    if type(self) == int:
        self.numer = self
        self.denom = 1
    return self.__truediv__(self.numer)
    return self.__truediv__(self.denom)

r1 = Rational(2,3)
r2 = Rational(1,4)
r3 = Rational(1,3)

assert Rational(2) == r1 / r3, "Division test failed."
assert Rational(3) == 1 / r3, "Division test failed."
4

1 に答える 1

2
 def __rdiv__(self,param):
    '''divide two reversed rationals'''
    # mapping is correct: if "(1) / (x/x)", 1 maps (to 1/1)
    if type(self) == int:
        self.numer = self
        self.denom = 1

type(self) == intが True と評価されることはありません。 で実行__rdiv__している場合Racional、 self は常に になりますRacionalparam代わりに、除算の左側 (この例では 1)をテストする必要があります。

于 2014-04-07T13:42:33.433 に答える