3

I am solving a programming problem, where i need to start at any given Position in an array/list and iterate till i am hitting the starting position. I thought about a circular buffer like approach (dequeue) but i am not sure if there is a iteration method, which does that.

Given:

[1,10,20]

So when i start iterating at position: 1 i want the iteration output to be:

10, 20, 1

My current solution:

startPosition = 1
data = [1,10,20]
for i in range(0, 3):
    pos = (startPosition+i)%3
    print data[pos]

Is there any other elegant solution? Or a container doing that?

Research:

I came across cycle from itertools but this is an endless loop.I would have to use the next method to get and stop at the correct position. Circular list iterator in Python

Community
  • 1
  • 1
user1767754
  • 23,311
  • 18
  • 141
  • 164

2 Answers2

4

As you mentioned you can use a deque which happens to be in the standard library:

from collections import deque

startPosition = 1
data = [1,10,20]

d = deque(data)
d.rotate(-startPosition)

You have to negate the direction of rotate because by default it does a rotation to the right.

Daniel
  • 26,899
  • 12
  • 60
  • 88
1

So elegant in programming is a bit subjective. Your code is easy to read/understand and the most efficient way of solving the given issue. There are certainly ways of writing your code in fewer bytes, but they may not be as legible as yours so I would not call them necessarily more elegant. And if you are looking for a faster way of solving the assigned problem,You have already achieved the problems best possible complexity of O(n).

satsuma
  • 60
  • 4