Created
November 18, 2010 16:48
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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