Skip to content

Instantly share code, notes, and snippets.

@yaotti
Created October 19, 2009 11:59
Show Gist options
  • Save yaotti/213312 to your computer and use it in GitHub Desktop.
Save yaotti/213312 to your computer and use it in GitHub Desktop.
Programming Pearls section 2
# -*- coding: utf-8 -*-
def rotate_arr(arr, t):
"""programming peals
rotate array algorithm(destructive)"""
l = len(arr)
tmp = arr[0]
k = 0
while True:
j = k
k = j+t
if k > l-1: k -= l
if k == 0:
arr[j] = tmp
break
arr[j] = arr[k]
return arr
a = [1,2,3,4,5]
print rotate_arr(a, 2) # => [3,4,5,1,2]
# -*- coding: utf-8 -*-
def rotate_arr(arr, t):
"""programming peals
rotate array algorithm(recursive, non-destructive)"""
if t == 0: return arr
l = len(arr)
if t * 2 < l:
(a, bl, br) = (arr[:t], arr[t:l-t], arr[-t:])
return rotate_arr(br+bl, len(br))+a
else:
(bl, br, a) = (arr[:l-t], arr[l-t:-l+t], arr[-l+t:])
return a+rotate_arr(br+bl, len(br))
a = [1,2,3,4,5]
print 'start: ', a
for i in range(1,5):
print rotate_arr(a, i)
# -*- coding: utf-8 -*-
def rotate_arr(arr, t):
"""programming peals
rotate array algorithm(most simple)"""
return (arr[:t][::-1]+arr[t:][::-1])[::-1] # arr[::-1] returns reversed arr
a = [1,2,3,4,5]
print 'start: ', a
for i in range(1,5):
print rotate_arr(a, i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment