Rotating a list

Question.
A list rotation consists of taking the first element and moving it to the end. For instance, if we rotate the list [1,2,3,4,5], we get [2,3,4,5,1]. If we rotate it again, we get [3,4,5,1,2].
Write a Python function rotatelist(l,k) that takes a list l and a positive integer k and returns the list l after k rotations. If k is not positive, your function should return l unchanged. Note that your function should not change l itself, and should return the rotated list.
Here are some examples to show how your function should work.

>>> rotatelist([1,2,3,4,5],1)
[2, 3, 4, 5, 1]

>>> rotatelist([1,2,3,4,5],3)
[4, 5, 1, 2, 3]

>>> rotatelist([1,2,3,4,5],12)
[3, 4, 5, 1, 2]

Solution:-

If the number of times to be rotated is greater than the length of list then we start iterating from n % size value till the end and append the elements to a new list, then append all the values in the list from beginning to the mod value - 1. Similar for the other case where k < len(l) as well but here instead of mod value, we make use of k only.



def rotatelist(l,n):
    nl = []
    if n > len(l):
        init = n % len(l)
        for i in range(init,len(l)):
            nl.append(l[i])
        for j in range(init):
            nl.append(l[j])
    else:
        for i in range(n,len(l)):
            nl.append(l[i])
        for j in range(n):
            nl.append(l[j])
    return nl

Comments

Popular posts from this blog

Prime partitioning a number

Alternating prime and square