python 数组翻转指定个数的元素
定义一个整型数组,并将指定个数的元素翻转到数组的尾部。
例如:(ar[], d, n) 将长度为 n 的 数组 arr 的前面 d 个元素翻转到数组尾部。
以下演示了将数组的前面两个元素放到数组后面。
原始数组:
翻转后:
实例 1
def leftrotate(arr, d, n):
for i in range(d):
leftrotatebyone(arr, n)
def leftrotatebyone(arr, n):
temp = arr[0]
for i in range(n-1):
arr[i] = arr[i+1]
arr[n-1] = temp
def printarray(arr,size):
for i in range(size):
print ("%d"% arr[i],end=" ")
arr = [1, 2, 3, 4, 5, 6, 7]
leftrotate(arr, 2, 7)
printarray(arr, 7)
for i in range(d):
leftrotatebyone(arr, n)
def leftrotatebyone(arr, n):
temp = arr[0]
for i in range(n-1):
arr[i] = arr[i+1]
arr[n-1] = temp
def printarray(arr,size):
for i in range(size):
print ("%d"% arr[i],end=" ")
arr = [1, 2, 3, 4, 5, 6, 7]
leftrotate(arr, 2, 7)
printarray(arr, 7)
以上实例输出结果为:
3 4 5 6 7 1 2
实例 2
def leftrotate(arr, d, n):
for i in range(gcd(d,n)):
temp = arr[i]
j = i
while 1:
k = j + d
if k >= n:
k = k - n
if k == i:
break
arr[j] = arr[k]
j = k
arr[j] = temp
def printarray(arr, size):
for i in range(size):
print ("%d" % arr[i], end=" ")
def gcd(a, b):
if b == 0:
return a;
else:
return gcd(b, a%b)
arr = [1, 2, 3, 4, 5, 6, 7]
leftrotate(arr, 2, 7)
printarray(arr, 7)
for i in range(gcd(d,n)):
temp = arr[i]
j = i
while 1:
k = j + d
if k >= n:
k = k - n
if k == i:
break
arr[j] = arr[k]
j = k
arr[j] = temp
def printarray(arr, size):
for i in range(size):
print ("%d" % arr[i], end=" ")
def gcd(a, b):
if b == 0:
return a;
else:
return gcd(b, a%b)
arr = [1, 2, 3, 4, 5, 6, 7]
leftrotate(arr, 2, 7)
printarray(arr, 7)
以上实例输出结果为:
3 4 5 6 7 1 2
实例 3
def rversearray(arr, start, end):
while (start < end):
temp = arr[start]
arr[start] = arr[end]
arr[end] = temp
start += 1
end = end-1
def leftrotate(arr, d):
n = len(arr)
rversearray(arr, 0, d-1)
rversearray(arr, d, n-1)
rversearray(arr, 0, n-1)
def printarray(arr):
for i in range(0, len(arr)):
print (arr[i], end=' ')
arr = [1, 2, 3, 4, 5, 6, 7]
leftrotate(arr, 2)
printarray(arr)
while (start < end):
temp = arr[start]
arr[start] = arr[end]
arr[end] = temp
start += 1
end = end-1
def leftrotate(arr, d):
n = len(arr)
rversearray(arr, 0, d-1)
rversearray(arr, d, n-1)
rversearray(arr, 0, n-1)
def printarray(arr):
for i in range(0, len(arr)):
print (arr[i], end=' ')
arr = [1, 2, 3, 4, 5, 6, 7]
leftrotate(arr, 2)
printarray(arr)
以上实例输出结果为:
3 4 5 6 7 1 2
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!