Swapping
A Programming Pattern (With Examples in Python)
Prof. David Bernstein
James Madison University
Computer Science Department
bernstdh@jmu.edu
Motivation
Frequently:
We need to swap the contents of two variables
A Context:
A fantasy role playing game in which players commonly acquire items of various kinds (e.g., weapons, spells, gold, food)
An Example of a Swap:
As the game progresses, two players meet and realize that it would benefit both of them to swap their swords
Review
The Assignment Operator:
Conceptually - Stores the right side operand in the memory location identified by the left side operand
Actually - Is a little more complicated than that (because references are used)
Variables:
Can only hold one "thing"
Review (cont.)
pythonexamples/programmingpatterns/Swapping.py
(Fragment: assignment)
A Defective Algorithm (cont.)
pythonexamples/programmingpatterns/Swapping.py
(Fragment: badswap)
Thinking About the Problem
Suppose:
You have Caladbolg in your right hand and Durendal in your left hand, and you want to swap them
To Make Progress:
You need a place to temporarily store one of the swords
The Pattern
The Idea:
Use another variable to temporarily hold the contents of one variable
pythonexamples/programmingpatterns/Swapping.py
(Fragment: swap)
The Pattern (cont.)
Example
pythonexamples/programmingpatterns/Swapping.py
(Fragment: swordswap)
The Example (cont.)
A Warning
The Idea:
Write a method that swaps the contents of its two parameters
The Issue:
To understand what is and isn't possible one must understand parameter passing mechanisms