A seemingly simple question. In retrospect, presumably designed to determine whether or not you think mathematically. I pondered, it's not a simple problem but not out of reach.
As research reveals this is a fairly common question with many good and bad answers. I believe I've found an illustrative solution:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MODULES
# VARIABLES
x = 20
y = 10
# FUNCTIONS
# Swap 2 vars: longhand method, the portable way:
def swapNosL(val1, val2):
print("BEFOR: val1: %r, val2: %r") % (val1, val2)
val1 = val1 + val2
val2 = val1 - val2
val1 = val1 - val2
print("AFTER: val1: %r, val2: %r") % (val1, val2)
return(val1, val2)
# Swap 2 vars: shorthand method, the non/less-portable way:
def swapNosC(val1, val2):
print("BEFOR: val1: %r and val2: %r") % (val1, val2)
val1, val2 = val2, val1
print("AFTER: val1: %r and val2: %r") % (val1, val2)
return(val1, val2)
# MAIN PROGRAM
print("")
print("The Problem:")
print("We need to swap 2 variables without using a 3rd.")
print("The values: 'x' is %r and 'y' is %r.") % (x, y)
print("")
(retVal1, retVal2) = swapNosC(x, y)
print("")
print("Now values: 'x' is %r and 'y' is %r.") % (retVal1, retVal2)
print"\n"
While there is some unnecessary repetition, the logic is solid. To baseline:
1) It works with all integers both positive and negative; I haven't tested floats yet.
2) The same memory is used 1 way or the other; only 2 variables are used either way.
3) Portability is (or should) always be a goal. In the case that programming languages go away and you need to port to a new one, research indicates that handling this problem mathematically will allow for greater portability.
In the "bad" example, this method is language-specific and porting to a language would (some day) require a different solution. I hope Python never goes the way of COBOL but the future is a big place.
However, in the "good" example the math is handled in a similar way in the C language. In fact, research also indicates math is generally handled the same way in most languages.
Therefore leaving the math in tact and only negotiating the syntax modification is the more portable method.
At some point I will concede to my friend that this was a good learning opportunity for me. But not for a while. I found the answer but failed by cheating with research.
TT