简化输出有理数python3

时间:2016-06-07 14:22:00

标签: class python-3.x fractions

我已经编写了一个程序,它读取了2个分数和一个运算符,并在评估时给出了答案。不要介意代码的长度,我只是将其添加完整。我的问题如下:当我输入

12/23
23/12
*

我希望它能给我输出1。但它给了我1/1。我怎么能纠正这个?

x = input().split('/')
y = input().split('/')
z = input()
def gcd ( a, b ):
    if  b == 0:
        return a
    else:
        return gcd(b, a%b)

class Rational:
    def __init__ ( self, a=0, b=1 ):
        g  =  gcd ( a, b )
        self.n  =  a / g
        self.d  =  b / g
    def __add__ ( self, other ):
        return Rational ( self.n * other.d + other.n * self.d,
                          self.d * other.d )
    def __sub__ ( self, other ):
        return Rational ( self.n * other.d - other.n * self.d,
                          self.d * other.d )
    def __mul__ ( self, other ):
        return  Rational ( self.n * other.n, self.d * other.d )
    def __div__ ( self, other ):
        return  Rational ( self.n * other.d, self.d * other.n )
    def __str__ ( self ):
        return "%d/%d" % ( self.n, self.d )
    def __float__ ( self ):
        return  float ( self.n ) / float ( self.d )

q = Rational()
w = Rational()
q.n = int(x[0])
q.d = int(x[1])
w.n = int(y[0])
w.d = int(y[1])
answer = eval("q"+z+"w")

1 个答案:

答案 0 :(得分:1)

由于在内部存储两个相等数字并不重要,因此您需要修改的唯一方法是__str__,它执行外部表示:

def __str__ ( self ):
    if self.d == 1:
        return "%d" % self.n
    return "%d/%d" % ( self.n, self.d )

这将正确处理n / 1的所有情况,包括1 / 1