Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Python để xoay một mảng theo chu kỳ

Cho một mảng đầu vào của người dùng. Nhiệm vụ của chúng ta là xoay theo chu kỳ nghĩa là xoay giá trị theo chiều kim đồng hồ.

Ví dụ

Input: A=[1,2,3,4,5]
Output=[5,1,2,3,4]

Thuật toán

Step 1: input array element.
Step 2: Store the last element in a variable say x.
Step 3: Shift all elements one position ahead.
Step 4: Replace first element of array with x.

Mã mẫu

# Python program to cyclically rotate
#an array by one
# Method for rotation
def rotate(A, n):
   x = A[n - 1]
   for i in range(n - 1, 0, -1):
      A[i] = A[i - 1];
   A[0] = x;
# Driver function
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the Element of  List ::")
for i in range(int(n)):
   k=int(input(""))
   A.append(k)
print ("The array is ::>")
for i in range(0, n):
   print (A[i], end = ' ')
rotate(A, n)
print ("\nRotated array is")
for i in range(0, n):
   print (A[i], end = ' ')

Đầu ra

Enter the size of the  List ::5
Enter the Element of  List ::
8
7
90
67
56
The array is ::>
8 7 90 67 56 
Rotated array is
56 8 7 90 67