-
In Python, how to swap two numbers without using a temp variable카테고리 없음 2017. 6. 25. 09:02
This is a very interesting question: How to swap two number variables without using a temp variable?
I have actually been asked this question while being interviewed for a job. Also this is a very well-known coding interview questions; therefore some books of interview preparation cover this question, for example, Cracking the Coding Interview. The answer is here.
x = x + y;
// x now becomes 15
y = x - y;
// y becomes 10
x = x - y;
// x becomes 5
However, while I was studying Problem Solving with Algorithms and Data Structures using Python, I found that in Python, this problem can be solved so simple as below:
left, right = right, left
You can check how this works here.