+ 39
[Python] Nasty in-place operators trick... 😏
I've been experimenting with a dataset lately and I've used algebraic in-place operators. I've been receiving incorrect output and I couldn't quite find the error. Suddenly it hit me... but let's start from the beginning: We all know that: x *= 2 is equivalent to: x = x * 2 For example: x = y = 4 x*=2 y = y * 2 print(x, y) >>> 8 8 But the equivalence ends here, since: x = y = 4 x*=2 + 1 y = y * 2 + 1 print(x, y) >>> 12 9 See here: https://code.sololearn.com/c6U6nrEn3DR0/ Consider yourself warned! 😉
7 Respuestas
+ 17
That's quite expected result for every programmer but not for mathematician, because priority of *= operation (any other of this type) is low and:
variable operator= expression
is equivalent to
variable = variable operator (expression)
But I upvoted it anyway to spread this information. :-)
BTW, you can add such task in Python game challenges, that will be a good one!
+ 7
All ok, because precedence of *= lower than precedence of *, so, and all calculation from right to left
+ 3
Wow, that’s... not what math says. I wonder how a calculator would handle this? I did the math in my head, weird.
Edit: the x*=2+1 is more like x(2+1), or 4(3), huh, guess it’s time to confuse some math teachers.
+ 2
it follows the BODMAS rule
+ 1
Yeah, it works on differently global list x, if you put x+=a, x=x+a in a function and input list x in func(x) where list a contains several members.