Skip to main content
 首页 » 编程设计

python之替换已弃用的 `fractions.gcd()` 函数

2024年09月07日7findumars

我想计算作为 fractions.Fraction 实例实现的两个有理数的最大公约数。尽管打印了弃用警告,但它按预期工作:

In [1]: gcd(Fraction(2, 3), Fraction(2, 3)) 
/usr/local/bin/ipython:1: DeprecationWarning: fractions.gcd() is deprecated. Use math.gcd() instead. 
  #!/usr/local/opt/python3/bin/python3.6 
Out[1]: Fraction(1, 6) 

查看 documentation我可以看到 fractions.gcd() 确实已被弃用,用户被邀请改用 math.gcd()。问题是后者不支持有理数:

In [2]: gcd(Fraction(2, 3), Fraction(2, 3)) 
--------------------------------------------------------------------------- 
TypeError                                 Traceback (most recent call last) 
<ipython-input-2-c3ad2389f290> in <module>() 
----> 1 gcd(Fraction(2, 3), Fraction(2, 3)) 
 
TypeError: 'Fraction' object cannot be interpreted as an integer 

我可以使用哪个函数来替换 fractions.gcd()?我不是在寻找此处使用的实际算法,而是在寻找已弃用函数的替代品。

请您参考如下方法:

您可能需要写一个。 gcd(a/b, c/d) = gcd(a, c)/lcm(b, d),所以这还不错。 math 没有提供 lcm,所以我使用的是写成 here 的那个.

from fractions import Fraction 
from math import gcd 
 
def lcm(a, b): 
    """Return lowest common multiple.""" 
    return a * b // gcd(a, b) 
 
def fraction_gcd(x, y): 
    a = x.numerator 
    b = x.denominator 
    c = y.numerator 
    d = y.denominator 
    return Fraction(gcd(a, c), lcm(b, d)) 
 
print(fraction_gcd(Fraction(2, 3), Fraction(2, 3))) 
# 2/3