For the following question, the function
• should mutate the original list
• should NOT create any new lists
• should NOT return anything
Functions that do not create new lists are said to be ”in place.” Such functions are often desirable because they do not require extra memory to operate.
Define shift_left, a function that takes a list and shifts each element in the list to the left by n indices. If elements start ”falling off” on the left, they are placed back on the right. NOTE: you may assume that n is a non-negative integer.
def shift_left(lst, n): """Shifts the elements of lst over by n indices. >>> lst = [1, 2, 3, 4, 5] >>> shift_left(lst, 2) >>> lst [3, 4, 5, 1, 2] """
Below is the solution:
def shift_left(lst, n):
"""Shifts the lst over by n indices
>>> lst = [1, 2, 3, 4, 5]
>>> shift_left(lst, 2)
>>> lst
[3, 4, 5, 1, 2]
"""
assert (n > 0), "n should be non-negative integer"
def shift(ntimes):
if ntimes == 0:
return
else:
temp = lst[0]
for index in range(len(lst) - 1):
lst[index] = lst[index + 1]
lst[index + 1] = temp
return shift(ntimes-1)
return shift(n)
I have yet to learn about raising exceptions in Python.
Can this code be more elegant by following a recursive approach? As of now, space (stack frame) usage can be considered secondary.