Python 程式以給定大小為分組來反轉一個數組?


這裡我們使用一個使用者輸入陣列和一個組的大小。我們按照組的大小建立子陣列並反轉它。如果各組的大小(p)不是陣列的大小(n)的倍數,那麼最後一組中會剩下少於 k 個元素,並且反轉所有剩餘元素。如果 p=1,則陣列保持不變;如果 p>=1,則反轉陣列中的所有元素。

演算法

Revarray(A,n,p)
/* A is an integer Array, n is the size of an array and every sub-array of size p starting from the beginning of the array and reverse it.*/
Step 1: i is the loop control variable which is initialized by 0.
Step 2: using while loop check i is less than n or not. If true
   Step 2.1: L=i	/* Left sub array
   Step 2.2: R=min (i+p-1, n-1)		/*Right sub array
   Step 2.3: Using while loop check L is than R or not. If yes
      Step 2.3.1: swap left sub array A (L) and Right Sub Array A(R).
      Step 2.3.2: L is incremented by 1.
      Step 2.3.3: R is stepping backward one step at a time.
	Step 2.4: End While
	Step 2.5: i=i+p
Step 3: End While
Step 4: Stop

示例程式碼

#reverse of an array in groups of given size
def arrayreverse(A, n, p):
   i = 0  
   while(i<n):
      L = i 
      R = min(i + p - 1, n - 1) 
      while (L < R):
         A[L], A[R] = A[R], A[L]
         L+= 1;
         R-+1
      i+= p
     
# Driver code
#Insert data in an array
A=list()
n=int(input("Enter the size of the array ::"))
print("Enter the number ::")
for i in range(int(n)):
   k=int(input(""))
   A.append(int(k))
    
p=int(input("Enter the size of the group ::"))
arrayreverse(A, n, p) 
for i in range(0, n):
   print(A[i], end =" ")         

輸出

Enter the size of the array ::6
Enter the number ::
11
22
33
44
55
66
Enter the size of the group ::2
22 11 44 33 66 55 

更新於: 30-Jul-2019

527 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.