+ 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! 😉

1st May 2018, 7:55 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
7 Answers
+ 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!
1st May 2018, 11:00 PM
Nevfy
+ 10
Nevfy, Petya Thanks for the replies, never had encountered it before, so that's why I was a bit astounded :) All clear now ;)
2nd May 2018, 10:04 AM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 7
All ok, because precedence of *= lower than precedence of *, so, and all calculation from right to left
1st May 2018, 9:58 PM
Petya soname
Petya soname - avatar
+ 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.
2nd May 2018, 2:12 PM
What was my name again?
What was my name again? - avatar
+ 2
it follows the BODMAS rule
30th Jun 2018, 7:43 AM
Sahil Danayak
Sahil Danayak - avatar
+ 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.
2nd May 2018, 6:16 PM
Lhak C:
Lhak C: - avatar