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_indsthe same length as the input arrays where each entry isTruewith 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
aandb, calleda_outandb_out, respectively usingnp.copy(). - Use Boolean indexing with the
swap_indsarray to swap the appropriate entries ofbintoa_outand ofaintob_out. - Return
a_outandb_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