Sunday, February 16, 2014

一维数组,向左/右 循环移动k位

Q:

一维数组,向左/右  循环移动k位


A:
   先全部reverse, 再[0,k-1] 和 [k, end] 分别reverse

代码
 #!/usr/bin/python
  2 def reverse(arr,low,high):
  3     while(low<high):
  4         arr[low],arr[high] = arr[high],arr[low]
  5         low+=1
  6         high-=1
  7 
  8 lst = [n for n in range(0,14)]
  9 print(lst)
 10     
 11 k = int(input("enter right shift number k = "))%len(lst)
 12 reverse(lst,0,len(lst)-1)
 13 reverse(lst,0,k-1)
 14 reverse(lst,k,len(lst)-1)
 15 
 16 print(lst)




No comments:

Post a Comment