satwikkansal / wtfpython

What the f*ck Python? 😱
Do What The F*ck You Want To Public License
35.51k stars 2.65k forks source link

Weird arithmetic with multiple `+` and `-` #319

Open hillairet opened 9 months ago

hillairet commented 9 months ago

Hello. Cool collection of WTFs I made a blog post about something that belongs in this collection.

I'd be happy to write up a section for it. Where should I put it? Any suggestion? Maybe right before or after the "Not knot" section that also deals with order precedence?

TL;DR This is all valid python:

>>> 1 +-+-+ 1
2
>>> 1 ++++++++++++++++++++ 1
2
>>> 1 ------- 1
0
>>> 1 ------ 1
2

It's all good an dandy until you use it with // and then things get weird:

>>> 2 + 5 // 2
4
>>> 2 -- 5 // 2
5

>>> 2 +-- 5 // 2
4
>>> 2 -+- 5 // 2
5
>>> 2 --+ 5 // 2
5

It's all explained by the operation precedence but it's very counter intuitive!

shiracamus commented 9 months ago

It's all explained by the operation precedence

Hmmmm

>>> 1 + (-(+(-(+1))))     # 1 + 1
2
>>> 1 + (+(+(+(+(+1)))))  # 1 + 1
2
>>> 1 - (-(-1))           # 1 - 1
0
>>> 1 - (-1)              # 1 - (-1) == 1 + 1
2
>>> +5 // 2
2
>>> -5 // 2
-3

>>> 2 + (5 // 2)          # 2 + (+5 // 2)
4
>>> 2 - ((-5) // 2)       # 2 - (-5 // 2)
5
>>> 2 + ((-(-5)) // 2)    # 2 + (+5 // 2)
4
>>> 2 - ((+(-5)) // 2)    # 2 - (-5 // 2)
5
>>> 2 - ((-(+5)) // 2)    # 2 - (-5 // 2)
5
hillairet commented 9 months ago

Thank you for the breakdown with parenthesis @shiracamus. I'm not too sure what to make of the comment "Hmmmmm" though.

There is clear operator precedence. Taking just this example:

>>> 2 - ((-(+5)) // 2)    # 2 - (-5 // 2)
5

The 2 signs - and + are applied to the 5 first, then // is performed, then the subtraction with 2 -. That matches the operator precedence table.

shiracamus commented 9 months ago

I'm not too sure what to make of the comment "Hmmmmm" though.

Its meaning is ``I try using parentheses to check the priority.''