Simulate Fisher-Yates Shuffling
Shuffle a copy of a list with Fisher-Yates: walk from the back and swap each position with a random earlier one, using given choices so the result can be checked.
The problem
The Fisher-Yates shuffle puts a list in a random order where every ordering is equally likely. To make the result checkable, the random choices are given to you. Implement fisher_yates(values, choices) and return a shuffled copy of values; do not change values itself. Let n = len(values). For i from n - 1 down to 1, take j = choices[n - 1 - i], a number from 0 to i (as if it came from random.randint(0, i)), and swap the items at positions i and j. Example: values = [1, 2, 3, 4], choices = [1, 0, 1]. i = 3 swaps with 1, giving [1, 4, 3, 2]; i = 2 swaps with 0, giving [3, 4, 1, 2]; i = 1 swaps with itself. The answer is [3, 4, 1, 2]. A list with fewer than two items has nothing to swap, and choices is then empty.
Starter code
def fisher_yates(values, choices):
passPublic examples
values = [1, 2, 3, 4], choices = [1, 0, 1]gives[3, 4, 1, 2]values = [1, 2, 3], choices = [2, 1]gives[1, 2, 3]
Solving it in the practice book needs an active paid plan.
Open it in the practice book