2017-03-03 14 views
-2

私は入門的なpythonクラスの宿題に取り組んでいます。 目的は*/+ - <> < => =クラス呼び出しの演算子を使用する関数を定義することです。この特定のプログラムは3つのパラメータself, inches, numerator, denominatorを取り、(それを簡素化することができる場合)組み込みクラス関数への演算子の割り当て

コールRulerUnit(2, 1, 4)私は乗算部に取り組んでいますし、トラブル時にを持っています"2 1/4"

を返す64の要因として分母を保存しますinches0

です。inches == 0またはinches is Noneですか?私のような主張を実行する場合は、とすることができるいずれさらに

assert(str(RulerUnit(2, 3, 4) * RulerUnit(0, 1, 2)) == "1 3/8")

AssertionErrorがrasedされ、自分のコード

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) 

答えて

0

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) 
0

値を保存する方法を正規化する必要があります。 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) 
+0

okを提案していただきありがとうございます。 –

関連する問題