gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:27:31 25 4
gpt4 key购买 nike

我想计算作为 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

关于python - 替换已弃用的 `fractions.gcd()` 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49981286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com