Swapping two values
Swap what two boxes hold, with the help of a spare box. About 8 minutes.
Two boxes, one problem
Say a holds 3 and b holds 8, and you want them to trade places. The obvious try is to copy b into a, then copy a into b.
The first line works: a now holds 8. But the 3 that used to be in a was thrown away. The second line copies 8 into b, and now both boxes hold 8. The 3 is lost for good.
a = b b = a # too late: a was already changed
The spare box
Think about swapping the juice in two glasses. You can't pour one into the other while both are full. You grab an empty third glass first.
In code, the empty glass is a spare variable, often called temp. Save one value there, overwrite that box, then put the saved value into the other box. Three lines, and nothing is lost.
temp = a a = b b = temp
- a
- 3
- b
- 8
Start: a holds 3, b holds 8, and the spare box is empty.
a holds 3 and b holds 8. You run a = b and then b = a, with no spare box. What do a and b hold?
- Aa holds 8 and b holds 8
- Ba holds 8 and b holds 3
- Ca holds 3 and b holds 8
Show the answer
a holds 8 and b holds 8. After the first line a holds 8, and the 3 is gone. The second line copies that 8 into b.
Swap the pair
Swap the two numbers using a spare variable, then return them as a list: first the new a, then the new b.
a = 3, b = 8 → [8, 3]
−1,000 ≤ a, b ≤ 1,000