开发者

What is the associativity of Python's ** operator?

开发者 https://www.devze.com 2022-12-22 10:39 出处:网络
I was just playing around with the python command line and the ** operator, which as far as I know performs a power function.So 2 ** 3 should be (and is) 8 because 2 * 2 * 2 = 8.

I was just playing around with the python command line and the ** operator, which as far as I know performs a power function. So 2 ** 3 should be (and is) 8 because 2 * 2 * 2 = 8.

Can so开发者_JAVA百科meone explain the behavior I found? I don't see any way to group the operations with parentheses to actually get a result of 65536 like was attained here.

>>> 2 ** 2 ** 2
16
>>> 2 ** 2 ** 2 ** 2
65536
>>> (2 ** 2 ** 2) ** 2
256


2** (2**(2**2))

from http://docs.python.org/reference/expressions.html

Operators in the same box group left to right (except for comparisons, including tests, which all have the same precedence and chain from left to right — see section Comparisons — and exponentiation, which groups from right to left).


Either it associates to the left or the right. To discover the answer yourself, do the experiment.

>>> 3 ** 3 ** 3
7625597484987
>>> (3 ** 3) ** 3
19683
>>> 3 ** (3 ** 3)
7625597484987

Thus, it associates to the right.

Or you can read the docs. google: "python power" and the first result is http://www.python.org/doc/2.5.2/ref/power.html

The second sentence is:

Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands).

Confirming the experimental results.


Also:

2 ** (2 ** 2 ** 2)

One way or the other, it becomes 2 ** 16.

This is following standard mathematical operations, where: 234 becomes 2 81, instead of 84 and thus is 2417851639229258349412352, instead of 4096.


The ** operator is right associative:

2 ** (2 ** (2 ** 2)) = 2 ** (2 ** 4) = 2 ** 16 = 65536

0

精彩评论

暂无评论...
验证码 换一张
取 消