是否已弃用`fractions.gcd()`函数?

时间:2018-04-23 12:38:01

标签: python python-3.x fractions

我想计算实现为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()?我不是在寻找这里使用的实际算法,而是替换已弃用的函数。

正如@glibdud在他的评论中所提到的,将fractions.gcd()与有理数一起使用并不是预期的行为,当然也没有记录......并且可以使用以下方法轻松实现:

def gcd(numbers):
"""Compute Greastest Common Divisor of rational numbers.

Args:
    numbers: list of rational numbers.

Returns:
    Greatest Common Divisor of rational numbers.
"""
# Treat the two-number case and reduce
def _gcd(a, b):
    if b == 0:
        return a
    if isinstance(a, int) and isinstance(b, int):
        _gcd(b, a % b)
    a = Fraction(a)
    b = Fraction(b)
    return Fraction(gcd([a.numerator, b.numerator]), lcm([a.denominator, b.denominator]))

return reduce(_gcd, numbers)

def lcm(numbers):
    """Compute Least Common Multiple of rational numbers.

    Args:
        numbers: list of rational numbers.

    Returns:
        Least Common Multiple of rational numbers.
    """
    # Treat the two-number case and reduce
    def _lcm(a, b):
        if b == 0:
            return a
        if isinstance(a, int) and isinstance(b, int):
            return a * b // gcd([a, b])
        a = Fraction(a)
        b = Fraction(b)
        return Fraction(lcm([a.numerator, b.numerator]), gcd([a.denominator, b.denominator]))

    return reduce(_lcm, numbers)

公式在此处得出并解释:https://math.stackexchange.com/questions/44836/rational-numbers-lcm-and-hcf

1 个答案:

答案 0 :(得分:2)

你可能要写一个。 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