Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python หมุนลิสต์ไปทางขวา n ตำแหน่ง

กำหนดลิสต์จากผู้ใช้และจำนวนการหมุน งานของเราคือหมุนลิสต์จากจำนวนการหมุนที่กำหนด

ตัวอย่าง

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 = []
    # นำ element ตัวท้าย num ตัวมาใส่ก่อน
    for item in range(len(my_list) - num, len(my_list)):
        output_list.append(my_list[item])
    # ตามด้วย element ที่เหลือ
    for item in range(0, len(my_list) - num):
        output_list.append(my_list[item])
    return output_list

# Driver Code
A = []
n = int(input("Enter the size of the List: "))
print("Enter the number")
for i in range(n):
    p = int(input("n="))
    A.append(p)
print(A)
rot_num = int(input("Enter rotate number: "))
print("After rotation:", right_rotation(A, rot_num))

วิธีที่ 2: ใช้ Slicing (แนะนำ - สั้นและเร็ว)

A = []
n = int(input("Enter the size of the List: "))
print("Enter the number")
for i in range(n):
    p = int(input("n="))
    A.append(p)
print(A)

n = 3
A = A[len(A) - n:len(A)] + A[0:len(A) - n]
print("After Rotation:", A)

วิธีที่ 3: ใช้ Negative Indexing (Pythonic มากที่สุด)

A = []
n = int(input("Enter the size of the List: "))
print("Enter the number")
for i in range(n):
    p = int(input("n="))
    A.append(p)
print(A)

n = 3
A = A[-n:] + A[:-n]
print("After Rotation:", A)

ผลลัพธ์ (ทุกวิธีให้ผลลัพธ์เดียวกัน)

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

สรุป

  • วิธีที่ 1 เข้าใจง่าย สำหรับผู้เริ่มต้น
  • วิธีที่ 2 ใช้ slicing แบบ explicit
  • วิธีที่ 3 ใช้ negative indexing A[-n:] + A[:-n] - แนะนำมากที่สุด เขียนสั้น อ่านง่าย ประสิทธิภาพดี

สำหรับการหมุนซ้าย (left rotate) ใช้ A[n:] + A[:n] หรือ A[n:] + A[:n]