Special Cases and Gotchas
Take care that your shuffle() function doesn’t add or remove any values to the list; it should
only rearrange the values already in the list. Because the shuffle() function modifies the values list
argument in-place, it doesn’t need to return anything. There shouldn’t be a return statement
anywhere in the function. In Python, all functions technically return a value; it’s just that functions
with no return statement return the value None.
When selecting a random index, select only an index within the range of the list’s indexes. This
means you should select an index from 0 up to, but not including, the length of the list. When calling
Python Programming Exercises, Gently Explained
119
random.randint()
to generate this random index, you’ll want to use 0 and len(values) - 1
to represent this range, and not 0 and len(values).
Now try to write a solution based on the information in the previous sections. If you still have
trouble solving this exercise, read the Solution Template section for additional hints.
Solution Template
Try to first write a solution from scratch. But if you have difficulty, you can use the following
partial program as a starting place. Copy the following code from https://invpy.com/randomshuffle-
template.py and paste it into your code editor. Replace the underscores with code to make a working
program:
# Import the random module for its randint() function.
import random
def shuffle(values):
# Loop over the range of indexes from 0 up to the length of the list:
for i in range(____(values)):
# Randomly pick an index to swap with:
swapIndex = random.randint(0, len(____) - ____)
# Swap the values between the two indexes:
values[i], values[swapIndex] = values[____], values[____]
The complete solution for this exercise is given in Appendix A and
https://invpy.com/randomshuffle.py. You can view each step of this program as it runs under a debugger
at https://invpy.com/randomshuffle-debug/.
|