Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating a list without using collection.deque

I want to make a script. The program should get some list L with values, and natural number N.
If N>0, the list's objects move N steps to left.
If N<0, the list's objects move abs(N) to the right.
If N=0 the list remain the same...

For example: For N=1 and L=[1,2,3,4,5], the output is [2,3,4,5,1].
For same list and N=-1 the output is [5,1,2,3,4]

I actually did it using collection.deque, but I want to do this with nothing but lists, for loop and 'if'.

I have problem to understand how to make the objects move.

l = input("enter list:")
N = input("enter number of rotations:")
import collections
d = collections.deque(l)
d.rotate(-N)
print d
like image 404
Amir Chazan Avatar asked Dec 03 '15 07:12

Amir Chazan


People also ask

How do you rotate items in a list?

To rotate the elements of a list, we can convert it to a deque object and then use the rotate() function. Below are some examples of how to rotate items in a list with the deque rotate() function. If you want to rotate the items multiple times, you just pass the number of times to rotate().

What does rotate function do in Python?

In this method, we just reassign the index to each value to specific position after rotation. The collections module has deque class which provides the rotate() , which is inbuilt function to allow rotation. This is lesser known function but has a greater utility.


Video Answer


1 Answers

You can use list slicing:

def rotate(L, N):
    if not L or N % len(L) == 0:
        return L
    return L[N % len(L):] + L[:N % len(L)]

L = [1, 2, 3, 4, 5]

for N in range(-3, 4):
    print(rotate(L, N))

Output:

[3, 4, 5, 1, 2]
[4, 5, 1, 2, 3]
[5, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 1]
[3, 4, 5, 1, 2]
[4, 5, 1, 2, 3]

Note that if you use a list, the time complexity of a rotation is linear to the number of elements in the list in general, since you have to move all existing elements. deque.rotate(), on the other hand, is O(k), with k being the number of steps. Therefore, if you need to rotate more than once deque.rotate() is the way to go.

like image 154
Eugene Yarmash Avatar answered Nov 10 '22 18:11

Eugene Yarmash