Answer to print(9 +-+-+-+ 2) in Python? #122966
-
Bodywhy does print(9 +-+-+-+ 2) give an answer of 7 in python? Guidelines
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hey @Vajeri , funky question :) In the Starting with a simpler example: a = 9 +- 2
a == 9 + (-2) == 7 Then, getting the result of the expression you provide is like solving one of these algebra exercises from school: a = 9 +-+-+-+ 2
= 9 + (- (+ (- (+ (- (+ 2))))))
= 9 (- (+ (- (+ (- 2)))))
= 9 (- (+ (- (- 2))))
= 9 (- (+ 2))
= 9 - 2 == 7 If this answers your question, please consider marking it as the answer :) |
Beta Was this translation helpful? Give feedback.
-
Let's break it down a bit: print(9 +- 7) The spacing makes it confusing, but it's print(9 + -7) Now the interesting thing is that 9 + (2).__neg__() When the 9 + (2).__neg__().__pos__() And all the other Also, even addition is a function call. (9).__add__((2).__neg__().__pos__()) So, you can write what you have as this to make it a bit more readable: left = 9
right = -+-+-+ 2
print(left + right) # 7 Here's an experiment: class MyInt(int):
"""
This class acts like an int, except it will print the function that gets called.
"""
def __add__(self, other):
print('add!')
return MyInt(super().__add__(other))
def __neg__(self):
print('neg!')
return MyInt(super().__neg__())
def __pos__(self):
print('pos!')
return MyInt(super().__pos__())
print(MyInt(9) +-+-+-+ MyInt(2)) |
Beta Was this translation helpful? Give feedback.
Hey @Vajeri , funky question :)
In the
+-+-+-+
string, the leftmost is treated as binary operator (taking two arguments) and the others modify the sign of 2.Starting with a simpler example:
Then, getting the result of the expression you provide is like solving one of these algebra exercises from school:
If this answers your question, please consider marking it as the answer :)