使用python简化有理数

use*_*258 1 python python-2.7 greatest-common-divisor

我正在研究python中处理有理数的问题,它有一个简化它的方法.例如12/8给出3/2.我已经完成了这个问题,并得到了正确的答案,但我已经找到了分子和分母的gcd.可能有人帮助使用一些内置的特殊python功能或函数,模块或python独有的任何东西,就像你说的"Pythonic方式!"

是否有这样的方法或任何测试案例应该包括在内以涵盖所有可能性?

这是我的代码:

class RationalNumber:
def __init__(self, n, d=1):
    self.n=n
    self.d=d

'''def gcd(self, a, b): // I have taken out gcd by two methods: recursion and while loop
    if b>a:
        t=a
        a=b
        b=t

    while a%b != 0:
        r=a%b
        a=b
        b=r

    return b
    '''

def gcd(self, a, b):
    if a%b==0:
        return b
    else:
        return self.gcd(b, a%b)

def simplify(self):
    x=self.gcd(self.n, self.d)
    self.n=self.n/x
    self.d=self.d/x

    return RationalNumber(self.n, self.d)

def __str__(self):
    print "%s/%s"%(self.n, self.d)

r1 = RationalNumber(12,8)
print r1.simplify()
Run Code Online (Sandbox Code Playgroud)

当我运行程序时,它会给出答案并给出错误:

Traceback (most recent call last):
  File "C:\Python27\CTE Python Practise\New folder\RationalNumberSimplify.py", line 42, in <module>
    print r1.simplify()
TypeError: __str__ returned non-string (type NoneType)
Run Code Online (Sandbox Code Playgroud)

请帮我删除错误并改进代码并使其更加pythonic!

str*_*nac 5

这样做有更多的pythonic方式.

分数模块有一个GCD()函数,但你很可能不会需要它,因为Fraction类应该做你想要的一切.

>>> import fractions
>>> print fractions.Fraction(12, 18)
2/3
Run Code Online (Sandbox Code Playgroud)