Skip to content

Instantly share code, notes, and snippets.

@lonnen
Created November 18, 2010 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lonnen/705260 to your computer and use it in GitHub Desktop.
Save lonnen/705260 to your computer and use it in GitHub Desktop.
An O(n) way to cycle a list. Inspired by Jon Bentley's 'Programming Pearls' in Chapter 2, 'Aha! Algorithms', section 2.3, 'Power of Primitives'. Less efficient than the three rotate method by a constant factor, but still interesting.
from fractions import gcd
def rotate(vector, k):
''' rotate the vector to the left '''
n = len(vector)
for i in range(gcd(k,n)):
temp = vector[i]
j = i
while True:
p = j + k
if p >= n: p = p-n
if p == i: break
vector[j] = vector[p]
j = p
vector[j] = temp
return vector
# vec = ['a','b','c','d','e']
# rotate(vec, 3) # output: ['d', 'e', 'a', 'b', 'c']
if __name__ == '__main__':
vec = ['a','b','c','d','e']
print ",".join(vec) + " -> rotate(vec, 3) -> " + ",".join(rotate(vec, 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment