Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Weird arithmetic with multiple + and - #319

Open
hillairet opened this issue Oct 2, 2023 · 3 comments
Open

Weird arithmetic with multiple + and - #319

hillairet opened this issue Oct 2, 2023 · 3 comments

Comments

@hillairet
Copy link

hillairet commented Oct 2, 2023

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
Copy link

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
Copy link
Author

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
Copy link

shiracamus commented Oct 4, 2023

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants