使用 python 简化有理数



我正在研究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()

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

Traceback (most recent call last):
  File "C:Python27CTE Python PractiseNew folderRationalNumberSimplify.py", line 42, in <module>
    print r1.simplify()
TypeError: __str__ returned non-string (type NoneType)

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

有一种更pythonic的方法可以做到这一点。

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

>>> import fractions
>>> print fractions.Fraction(12, 18)
2/3

使用 @stranac 提到的分数模块。至于您关于错误的其他问题,可以通过将__str__的方法替换为

def __repr__(self):
    return "%s/%s"%(self.n, self.d)

对于__str____repr__,您需要返回一个字符串,而不是简单地将其打印出来。查看以下问题可能会有所帮助:

Python 中__str__和__repr__的区别

最新更新