Efficient Way to Rotate a List in Python

Efficient way to rotate a list in python

A collections.deque is optimized for pulling and pushing on both ends. They even have a dedicated rotate() method.

from collections import deque
items = deque([1, 2])
items.append(3) # deque == [1, 2, 3]
items.rotate(1) # The deque is now: [3, 1, 2]
items.rotate(-1) # Returns deque to original state: [1, 2, 3]
item = items.popleft() # deque == [2, 3]

What is the Efficient way to right rotate list circularly in python without inbuilt function

You'll probably run into a timeout when you concatenate large lists with temp = a + a.

Instead, don't create a new list, but use the modulo operator in your loop:

   print(a[(indexToCountFrom+val) % len(a)])

program to rotate list of numbers until all numbers have moved back to origional position

You can use the input function to get user input. The input would be a string so you would then have to split it using str.split method to create a list from the input.

like this:

user_input = input("Input a list: ")  # input = '1 2 3 4'
seq = user_input.split() # seq = ['1','2','3','4']

def rotation(nums):
for i in range(len(nums)+1):
rotated = nums[i:] + nums[:i]
print(','.join(rotated))


rotation(seq)

Im trying to rotate a list using Python by two each time

Your approach is a bit too convoluted. You should try a different approach.

For eg:
A simple slicing operation would work just fine here.

def rotateRight(no_of_rotations):
arr = [1, 2, 3, 4, 5]
arr = arr[no_of_rotations:] + arr[:no_of_rotations]
return arr

All the best! :)

Quickly rotating list of points in Python

EDIT:

numpy operates on np arrays much faster. Consider converting your lists to numpy arrays.

In [72]: L1                                                                                     
Out[72]: [[1.1, 2.3, -5.5], [3.4, 2.0, 3.0]]

In [73]: R1
Out[73]:
[[0.99214145, -0.09280282, -0.08392241],
[-0.09280282, -0.09592336, -0.99105315],
[0.08392241, 0.99105315, -0.10378191]]

In [75]: %timeit np.dot(L1, R1)
7.81 µs ± 30 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [76]: L2 = np.array(L1)

In [78]: R2 = np.array(R1)

In [79]: %timeit np.dot(L2, R2)
1.51 µs ± 7.72 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [80]: %timeit L2 @ R2
3.35 µs ± 12.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

OLD ANSWER:

You may consider applying your own dot product function too.

In [8]: from operator import mul

In [11]: %timeit sum(map(mul, L1[0], R1[0])) # just to see how long it takes
873 ns ± 1.82 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [6]: %timeit np.dot(L1[0], R1)
5.63 µs ± 29.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

I'm not into numpy much, there might be more optimal solutions though, but one thing for sure is np shines where you have huge amounts of data to operate on. If you're dealing with relatively small arrays etc, handmade solutions might be better options.

Rotating a list n times when n is greater than the number of elements in list

Apply modulo to the argument:

def shift(l,n):
if not len(l): # to avoid error on modulo operator
return []
n = n % len(l)
return l[n:] + l[:n]

Shift elements of a list forward (rotating a list)

You can use slicing by just joining the later sliced part to the initial sliced part given the rotation number.

inp = input().split()
shift_by = int(inp[-1])
li = inp[:-1]

print(li[shift_by:] + li[:shift_by]) # ['four', 'five', 'six', 'seven', 'one', 'two', 'three']

Is there a way to rotate values in a list but every 3rd position on the list is stationary?

From your expected output, you need to keep every 2nd element of the list, which can be extracted by [::2]:

rotate = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
rotate[::2]
#[1, 3, 5, 7, 9, 11]

The other elements which require shuffling can be extracted by [1::2]:

rotate[1::2]
#[2, 4, 6, 8, 10, 12]

Now you just need to move the last element of the 2nd list to the top. There are many ways to do it, but I got lazy and use the below:

result = [rotate[1::2].pop(-1)] + rotate[1::2][:-1]

Then you can join the amended lists together:

r = [(a,b) for a,b in zip(rotate[::2],result)]
r = [x for i in r for x in i]
r
#[1, 12, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10]


Related Topics



Leave a reply



Submit