Lecture 3 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.
Question 1.
Implement a function For example, when rotate_list() that satisfies the docstring given below.def rotate_list(items, shift):
"""
Shift the elements of a list, rotating elements from one end to the other.
Parameters:
items (list): A non-empty list.
shift (int): The number of index positions to move each element.
If shift is positive, move elements forward to the right;
if negative, move them backward to the left.
Return a new list with the same elements as items, but translated
according to shift. If shift causes an element to go past the end of
the list, cycle the element around to the beginning, or vice versa.
"""
items = [1, 2, 3, 4, 5]:
rotate_list(items, 2) should evaluate to [4, 5, 1, 2, 3]rotate_list(items, -2) should evaluate to [3, 4, 5, 1, 2]rotate_list(items, 6) should evaluate to [5, 1, 2, 3, 4]
Question 2.
Re-implement the function For example, when rotate_list() from above, but now mutate the input list, rather than return a new list.def rotate_list(items, shift):
"""
Shift the elements of a list, rotating elements from one end to the other.
Parameters:
items (list): A non-empty list.
shift (int): The number of index positions to move each element.
If shift is positive, move elements forward to the right;
if negative, move them backward to the left.
MUTATE the items list so that its elements are translated according
to shift. If shift causes an element to go past the end of the list,
cycle the element around to the beginning, or vice versa.
"""
items = [1, 2, 3, 4, 5]:
rotate_list(items, 2), items should evaluate to [4, 5, 1, 2, 3]rotate_list(items, -2), items should evaluate to [3, 4, 5, 1, 2]rotate_list(items, 6), items should evaluate to [5, 1, 2, 3, 4]