0

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]

i have tried solving it but the desired output is not coming

This is my code but it shows different output

def rotatelist(l,k): 
    if(k>0):
        o=-1
        p=1

        while(o<=k):
            x=l.pop(p)
            l.insert((p-1),x)
            o+=1
    else:
        return(l)
    return(l) 

Input

list([1,2,3,4,5],1)

Expected Output

[2, 3, 4, 5, 1]

Actual Output

[2, 1, 3, 4, 5]
Martin
  • 3,333
  • 2
  • 18
  • 39
Anish Mazumdar
  • 315
  • 1
  • 4
  • 8
  • There are a few things wrong here, but notably you're violating the constraint that "your function should not change l itself". You'll need to try a different approach (or at least make a copy of `l` first). – glibdud Feb 11 '19 at 19:59

1 Answers1

-1

Use this code:

def rotatelist(l, k):
    n = len(l)
    if k < 0:
        return l
    d=l
    while(k>0):
        temp=d[0]
        for i in range(n-1):
            d[i]=d[i+1]
            d[i+1]=temp
        k=k-1
    return d
  • erm `l.append(l.pop())` does nothing useful. `pop` returns the last element, that you append again. Consider 1) testing your code 2) explaining your code (and 3, look for duplicates before answering classics like this, even if it's difficult at first) – Jean-François Fabre Feb 11 '19 at 20:07
  • I have edited the above code please see it – Maheshwar Kuchana Feb 12 '19 at 14:49