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

Chương trình Python xoay sang phải một danh sách theo n

Đưa ra danh sách đầu vào của người dùng và số vòng quay. Nhiệm vụ của chúng tôi là xoay danh sách từ số vòng quay đã cho.

Ví dụ

Input A= [2, 4, 5, 12, 90]
rotation number=3
Output [ 90,12,2, 4, 5]

Phương pháp1

Ở đây, chúng tôi duyệt qua từng phần tử trong danh sách và chèn phần tử vào những vị trí cần thiết trong danh sách thứ hai.

Ví dụ

def right_rotation(my_list, num): 
   output_list = []
   for item in range(len(my_list) - num, len(my_list)):
      output_list.append(my_list[item])
   for item in range(0, len(my_list) - num):
      output_list.append(my_list[item])
   return output_list
# Driver Code
A=list()
n=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(n)):
   p=int(input("n="))
   A.append(int(p))
   print (A)
rot_num=int(input("Enter rotate number"))
print("After rotation",right_rotation(A, rot_num))
python54.py

Đầu ra

Enter the size of the List 6
Enter the number
n= 11
[11]
n= 22
[11, 22]
n= 33
[11, 22, 33]
n= 44
[11, 22, 33, 44]
n= 55
[11, 22, 33, 44, 55]
n= 66
[11, 22, 33, 44, 55, 66]
Enter rotate number 3
After rotation [44, 55, 66, 11, 22, 33]

Phương pháp2

Ở đây chúng tôi áp dụng kỹ thuật cắt bằng len ().

A=list()
ni=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(ni)):
   p=int(input("ni="))
   A.append(int(p))
   print (A)
n = 3
A = (A[len(A) - n:len(A)] + A[0:len(A) - n])
print("After Rotation",A)

Đầu ra

Enter the size of the List 6
Enter the number
ni= 11
[11]
ni= 22
[11, 22]
ni= 33
[11, 22, 33]
ni= 44
[11, 22, 33, 44]
ni= 55
[11, 22, 33, 44, 55]
ni= 66
[11, 22, 33, 44, 55, 66]
After Rotation [44, 55, 66, 11, 22, 33]

Phương pháp3

Trong phương pháp này, n phần tử cuối cùng của danh sách A được lấy và sau đó là các phần tử còn lại của danh sách A.

Ví dụ

A=list()
ni=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(ni)):
   p=int(input("ni="))
   A.append(int(p))
   print (A)
n = 3
A = (A[-n:] + A[:-n])
print("After Rotation",A)

Đầu ra

Enter the size of the List 6
Enter the number
ni= 11
[11]
ni= 22
[11, 22]
ni= 33
[11, 22, 33]
ni= 44
[11, 22, 33, 44]
ni= 55
[11, 22, 33, 44, 55]
ni= 66
[11, 22, 33, 44, 55, 66]
After Rotation [44, 55, 66, 11, 22, 33]