我想计算两个作为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)查看文档,我可以看到,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()?我不是在寻找这里使用的实际算法,而是替代不推荐的函数。
发布于 2018-04-23 12:58:33
你可能得写一个。gcd(a/b, c/d) = gcd(a, c)/lcm(b, d),所以这不算太糟。math不提供lcm,所以我使用的是编写的这里。
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发布于 2022-04-06 02:18:38
注:以下内容最初由原海报编辑成问题正文。我把它移到了另一个答案。
正如@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。
https://stackoverflow.com/questions/49981286
复制相似问题