Lecture 5 Finger Exercise
Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.
For example, consider a scenario where walk(n, leftbound, rightbound, leftbias) that meets the specification below.
You do not need to import random; the server will import it for you.
You also should not call random.seed(); the server will ignore any lines containing that text.
def walk(num_steps, leftbound, rightbound, leftbias=0.5):
"""
Perform a random walk along the real number line, starting from 0.
Parameters:
num_steps (int): The number of steps to run the random walk.
leftbound (int): A negative number location that the walk may not go past.
rightbound (int): A positive number location that the walk may not go past.
leftbias (float): A value between 0 and 1 inclusive.
Each step attempts to go either one unit left (-1) with probability
leftbias, or one unit right (+1) otherwise.
The walk may go up to, but not beyond, leftbound or rightbound.
Attempting to go left while at leftbound leaves the location unchanged;
similarly for going right at rightbound. Each time step for which
the walk reaches or remains at either bound counts as a wall hit.
After completing num_steps steps, return a two-element list, where
the first element is the total number of wall hits, and the second
is the final location.
"""
# your code here
leftbound = -1 and rightbound = 1.
Suppose a walk of n = 4 steps results in the sequence of locations 0 → -1 → -1 → 0 → 1.
This would count as three wall hits, with a final location of 1.
For example, suppose reorder_using_index(sequence, func).
This function allows you to sort a list using a rule that cares about both the value of the item and its original position in the list.
You may assume that there will be no need for a tiebreaker.
def reorder_using_index(sequence, func):
"""
Reorder a sequence based on a scoring function that takes a list
of the form [index, element] as an input.
Parameters:
sequence (list): A list of elements.
func (function): A function that takes a list of the form
[index, element] and returns a number to be used as a
sorting key.
Return a new list containing the original elements of the sequence,
reordered in increasing order of the scores produced by func.
"""
# your code here
sequence = [10, 2, 8] and func returns 2 * index + element.
The elements are scored as: 10 → 10, 2 → 4, and 8 → 12.
Sorting by these scores in increasing value results in the final list [2, 10, 8].