+ 4
3 ** 1 ** 2 ** 4 == 3. ... Wait, what?
In my understanding, Python calculates operations with higher operator precedence first, and those of equal OP from left to right. Somehow this doesn't seem to happen in the example (from a challenge) ... I expected 3**1=3; 3**2=9; 9**4=6,561. Can someone please explain?
10 Respuestas
+ 1
This just the way exponential works. It will be easier to understand writing exponential on a paper sheet. On the computer, it seems that exponential is like any operator, figures are on the same level on each side of the operator.
But try writing 3**1**2**4 like it's supposed to be written on a sheet of paper, and visually, you'll understand exponential are not symmetrical.
Exponential is place at the top right of number. Thus exponential applies to the number that is at the bottom left of the exponential. In 3**1**2**4, you'll have several levels of exponentials.
At the bottom left of 4 there is 2. If you want to raise 3**1**2 to the power of 4, you'll need to write (3**1**2)**4.
And so on for each exponential level.
+ 5
3 ** 1 ** 2 ** 4 == 3 it will return `true` as operations happens from right to left
+ 4
3**(1**2**4) = 3**(1**(2**4)) = 3**(1**(16)) = 3**1 = 3
Open browser console and run it
+ 3
python works it' way out from the inner to the outer shell of the problem. That is why 2**4 comes first.
+ 3
On a piece of paper might write this as:
4
2
1
3
this however would be equal to 3**(1*2*4) = 3**8, no?
+ 2
It's actually like math. Your example respects the order of the exponential operator.
In your case, 3 ** 1 ** 2 ** 4:
- 2 is raised to the 4th power, which makes 16.
- Then 1 is raised to the 16th power, which makes 1.
- And 3 is raised to the power of 1, which makes 3.
To verify this, try 3**2**4 and try 3**16. In both case you will find 43,046,721, which is different from 6,561 from your line "3**2=9; 9**4=6,561"
+ 2
roots are exponentials as sqrt(x) = x**(1/2) so they should behave in the same way.
0
Okay, but why is it that the rightmost part of the chain comes first? (School math was long ago, I must have forgotten.)
0
Thank you, it really helps to see it on paper. :)
I just tried it with roots - same pattern. Interesting...
Maybe I should refresh my school math.
0
power op is reads right to left, this namef op associaton. like list concatenation in Scala, one can say