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/.