Generating permutation samples
As you worked out in the last exercise, we need to generate a permutation sample by randomly swapping corresponding entries in the semi_times
and final_times
array. Write a function with signature swap_random(a, b)
that returns arrays where random indices have the entries in a
and b
swapped.
This exercise is part of the course
Case Studies in Statistical Thinking
Exercise instructions
- Define a function with signature
swap_random(a, b)
that does the following.- Create an array
swap_inds
the same length as the input arrays where each entry isTrue
with 50/50 probability. Hint: Usenp.random.random()
with thesize=len(a)
keyword argument. Each entry in the result that is less than 0.5 should beTrue
. - Make copies of
a
andb
, calleda_out
andb_out
, respectively usingnp.copy()
. - Use Boolean indexing with the
swap_inds
array to swap the appropriate entries ofb
intoa_out
and ofa
intob_out
. - Return
a_out
andb_out
.
- Create an array
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
def ____(____, ____):
"""Randomly swap entries in two arrays."""
# Indices to swap
swap_inds = ____ < ____
# Make copies of arrays a and b for output
a_out = ____
b_out = ____
# Swap values
____[____] = ____[____]
____[____] = ____[____]
return a_out, b_out