사용자 입력 목록이 주어지고 회전 수가 주어집니다. 우리의 임무는 주어진 회전 수에서 목록을 회전하는 것입니다.
예시
Input A= [2, 4, 5, 12, 90] rotation number=3 Output [ 90,12,2, 4, 5]
방법 1
여기에서 목록의 각 요소를 탐색하고 두 번째 목록의 필요한 위치에 요소를 삽입합니다.
예시
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
출력
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]
방법 2
여기서는 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)
출력
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]
방법 3
이 방법에서는 목록 A의 마지막 n개 요소를 가져온 다음 목록 A의 나머지 요소를 가져옵니다.
예시
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)
출력
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]