Get startedGet started for free

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

View Course

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 is True with 50/50 probability. Hint: Use np.random.random() with the size=len(a) keyword argument. Each entry in the result that is less than 0.5 should be True.
    • Make copies of a and b, called a_out and b_out, respectively using np.copy().
    • Use Boolean indexing with the swap_inds array to swap the appropriate entries of b into a_out and of a into b_out.
    • Return a_out and b_out.

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
Edit and Run Code