Skip to main content
 首页 » 编程设计

python之使用 python 简化有理数

2025年05月04日17xing901022

我正在用 python 处理有理数问题,它有一种方法可以简化它。例如 12/8 给出 3/2。我已经完成了那个问题并得到了正确答案,但我是通过找到分子和分母的 gcd 来完成的。当你说“Pythonic 方式!”时,有人可以使用一些内置的特殊 Python 特性或函数、模块或 Python 独有的任何东西来帮助完成它吗?

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

这是我的代码:

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:\Python27\CTE Python Practise\New folder\RationalNumberSimplify.py", line 42, in <module> 
    print r1.simplify() 
TypeError: __str__ returned non-string (type NoneType) 

请帮助我消除错误并改进代码并使其更符合 Python 风格!

请您参考如下方法:

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

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

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