Problem Solving
Lists
Rotate:
def rotate(l, k):
for i in range(k):
l.insert(0, l.pop())
return l
# option 2:
def rotate_alternative(lst, degree):
rotation = degree % len(lst)
return lst[-rotation:] + lst[:-rotation]
Optimized version:
# Idea behind this:
# <> marks selected elements
# 2 rotations
['a', 'b', 'c', 'd', 'e', 'f']
# reverse first 2
[<'b', 'a',> 'c', 'd' ,'e', 'f']
# reverse all but first 2
['b', 'a', <'f', 'e', 'd', 'c'>]
# reverse all
[<'c', 'd', 'e', 'f', 'a', 'b'>]
# all done!
['c', 'd', 'e', 'f', 'a', 'b'
def rev(lst, low, high):
while low < high:
lst[low], lst[high] = lst[high], lst[low]
high -= 1
low += 1
return lst
def rotate(my_list, num_rotations):
# Reverse first num_rotations
rev(my_list, 0, num_rotations-1)
# Reverse all but num_rotations
rev(my_list, num_rotations, len(my_list)-1)
# Reverse all
rev(my_list, 0, len(my_list)-1)
return my_list
Last updated