Python Programming Exercises,
Gently Explained
118
shuffled list must contain the same values as before but in random order.
This exercise asks you to implement a function identical to Python’s random.shuffle()
function. As such, avoid using this function in your solution as it’d defeat the purpose of the exercise.
These Python assert statements stop the program if their condition is False. Copy them to
the bottom of your solution program. Your solution is correct if the following assert statements’
conditions are all True:
random.seed(42)
# Perform this test ten times:
for i in range(10):
testData1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(testData1)
# Make sure the number of values hasn't changed:
assert len(testData1) == 10
# Make sure the order has changed:
assert testData1 != [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Make sure that when re-sorted, all the original values are there:
assert sorted(testData1) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Make sure an empty list shuffled remains empty:
testData2 = []
shuffle(testData2)
assert testData2 == []
Try to write a solution based on the information in this description. If you still have trouble
solving
this exercise, read the
Solution Design and Special Cases and Gotchas sections for
additional hints.
Prerequisite concepts: import statements, random module, randint(), for loops, range(),
len()
,
swapping values
Solution Design
The solution is surprisingly straightforward. A for loop can loop over every index in the list. On
each iteration, the code in the loop selects a random index. Then it swaps the values at the current
iteration’s index and the random index.
If the random index is the same as the current iteration’s index, this is fine: a random shuffling
can include values at their original location. This isn’t somehow ―less random‖ than any other
permutation. If the random index is a repeat of an index that
has previously been swapped, this is fine
as well. Shuffling a value to a random location twice isn’t any more or less shuffled than moving a
value to a random location once.
Dostları ilə paylaş: