【问题标题】:What is the difference between Python's built-in `pow` function and the `**` operator?Python 内置的 `pow` 函数和 `**` 运算符有什么区别?
【发布时间】:2020-03-07 17:43:55
【问题描述】:

如果有**运算符,为什么pow函数存在? 比函数还要快:

from timeit import timeit
print(timeit('pow(3000, 3000)', number=10000))
print(timeit('3000**3000', number=10000))

输出:

1.3396891819999155
1.3082993840000654

【问题讨论】:

  • 点击链接,阅读问题,您的所有疑问都会casted away in the wind。 ;)
  • @hitter - 根据您的链接问题回忆,math.pow 函数不等效。
  • @tdelaney 好的,这越来越累了。看,我没有看到你的用户名,你用一种居高临下的语气问道,这通常是提问者。我看你是一个高代表用户。这意味着 a) 您有足够的经验来找到答案; b) 如果您发现它与我标记的不同,则将其标记为新副本。
  • 注意:我们有 2 票赞成 dup,但显然不是。这是一个很好的问题,一个答案就是**pow 有细微的不同。除非您找到质量更好的副本,否则请不要关闭它。

标签: python pow


【解决方案1】:

我发现pow 函数比** 运算符更有用。首先,** 确实是升幂并应用可选模数,如a**b % c。但是如果包含%,它的值就不能是None2**3 % None 是一个错误。 pow 真的是 pow(x, y, z=None)

所以,如果我想将派生值提升为幂,我可以使用运算符

>>> def powerizer(db, index, modulus=None):
...     x, y = db.get(index)
...     return x**y % modulus
... 
>>> db = {"foo":[9,3]}
>>> powerizer(db, "foo", 10)
9

但它在默认的None 模数上失败。

>>> powerizer(db, "foo")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in powerizer
TypeError: unsupported operand type(s) for %: 'int' and 'NoneType'

pow 救援功能

>>> def powerizer(db, index, modulus=None):
...     x, y = db.get(index)
...     return pow(x, y, modulus)
... 
>>> powerizer(db, "foo", 10)
9
>>> powerizer(db, "foo")
729

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2011-07-07
    • 1970-01-01
    • 2018-08-16
    • 2012-10-10
    • 2010-11-15
    • 1970-01-01
    相关资源
    最近更新 更多