繁体   English   中英

Python 内置的 `pow` 函数和 `**` 运算符有什么区别?

[英]What is the difference between Python's built-in `pow` function and the `**` operator?

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

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

输出:

1.3396891819999155
1.3082993840000654

我在**运算符上找到了pow函数的一种用途。 首先, **实际上是提升到一个幂并应用一个可选的模数,如a**b % c 但是如果你包含% ,它的值不能是None 2**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

暂无
暂无

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

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