繁体   English   中英

取分数的倒数

[英]Taking the reciprocal of a Fraction

我想在 python 中取Fraction的倒数,并就地执行。 Fraction class 没有提供这样做的方法(据我所知)。 我试图交换分子和分母:

f = Fraction(2, 3)
f.numerator, f.denominator = f.denominator, f.numerator

但它导致了AttributeError: can't set attribute

我还使用了仅构造一个新Fraction的方法:

f = Fraction(2, 3)
f = Fraction(f.denominator, f.numerator)

这确实有效,但是创建一个新的 object 并删除旧的似乎不是很“pythonic”,即不必要的复杂。 有没有更好的方法来取反?

from fractions import Fraction

spam = Fraction(2, 3)
eggs = spam ** -1
print(repr(eggs))

output

Fraction(3, 2)

编辑:正如@martineau 1 / spam的评论中所建议的那样:

from fractions import Fraction

spam = Fraction(2, 3)
eggs = 1 / spam 
print(repr(eggs))

我认为f**-1这将完成这项工作

Fractions像许多(全部?)Python 数字一样是不可变的,这就是为什么您不能更改它们的属性的原因。 解决方法是定义一个 function,它根据传递给它的属性创建并返回 class 的实例。 下面显示了两种方法。

from fractions import Fraction


def reciprocal(f):
    """ Return reciprocal of argument (an instance of Fraction). """
    return Fraction(f.denominator, f.numerator)

# Alternative implementation.
reciprocal = lambda f: Fraction(f.denominator, f.numerator)


f = Fraction(2, 3)
print(f)  # -> 2/3
print(repr(f))  # -> Fraction(2, 3)
r = reciprocal(f)
print(r)  # -> 3/2
print(repr(r))  # -> Fraction(3, 2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM