Swapping The Values Of Two Variables
One of the
classic problems that can be encountered in programming is
swapping the values of two variables. It may seem trivial, but there are quite a few tricks!
EXAMPLE
Let's assume we have two glasses, labeled
A and
B, each containing
70 and
40 ml of liquid respectively:
How do we swap their contents? We can use a third glass
for maneuvering, called
C,
which is initially empty:
Step 1. Pour the contents of
A into
C:
Step 2. Then pour the contents of
B into
A:
Step 3. Finally, pour the contents of
C into
B:
Glass
C is empty again, and we have succeeded!
The algorithm translated into
Python is as follows:
Attention. Unlike glasses, where we use a mechanical process, at the end of the program the variable
C will hold
the last value, which is now stored by
B. In the program, we
copy values and do not pour them! 😜
Temporary /
intermediate variables do not matter in the output,
they are used to perform calculations
within the program, like
C.
HOW CAN WE MAKE A MISTAKE?
Simple. Consider the sequence below:
A = B #A holds 40
B = A #B will hold 40 again
The first assignment loses the content of
A permanently...
ANOTHER METHOD
Anyone who says that computer science doesn't require
mathematics is seriously mistaken.
Swapping can also be done
without another temporary variable! Try the code below, for example:
A = A + B #A holds 110
B = A - B #B will hold 70
A = A - B #A will hold 40
PYTHON IS AWESOME!
The creators of the language anticipated this need, so we can use the following type of assignment:
A, B = B, A
Elegant, isn't it? 😎
Run the program and read the information.