LESSON 5
|
PAGE 2/4
|

Interchange values of two variables
One of the classic problems that can be encountered when creating programs is interchange
values of two variables (swapping). It may seem trivial, but there are some tricks!
EXAMPLE
Suppose we have two glasses, marked with A and B, containing each 70 and respectively 40 ml of liquid:

How do we exchange content? We can use a third maneuvering glass, called C, which is initially empty:

Step 1. We pour the contents of A in C:

Step 2. We pour the contents of B in A:

Step 3. Finally, we pour the contents of C in B:

The C glass is empty again, and we did it!
The algorithm transposed in Python 3 is therefore as follows: Warning. Unlike glasses, where we use a mechanical process, at the end of the program the variable C will hold the last value, that is, the one now held by B. In the program we copy the values and do not pour them! 😜
Maneuvering variables do not count on output, but are used to perform calculations within the program, such as C.
HOW CAN WE GET IT WRONG?
Simple. We consider the following sequence sufficient:
A = B #A retains 40
B = A #B will retain 40 again
First assignment loses A content permanently...
ANOTHER METHOD
Whoever tells you that computer science does not require mathematics is sorely mistaken. Interchange can be performed without another maneuver variable! Test the example below:
A = A + B #A retains 110
B = A - B #B retains 70
A = A - B #A retains 40
PYTHON IS SUPER!
The language creators anticipated this need, so we can use the following type of assignment:
A, B = B, A
Elegant, right? 😎
Run the program and read the information.

home | list LESSONS | arrow_upward |