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

โปรแกรม Python กลับลำดับอาร์เรย์ถึงตำแหน่งที่กำหนด


กลับลำดับ sub-array จาก index 0 ถึง n-1 ของอาร์เรย์ที่ผู้ใช้ป้อน

ตัวอย่าง

Input: A=[3,7,6,4,1,2], n=4
Output: [1,4,6,7,3,2]

อัลกอริทึม

  1. กลับลำดับส่วนแรก n อิลิเมนต์: A[n-1::-1]
  2. ต่อกับส่วนที่เหลือ: A[n:]
  3. รวมกัน

โค้ดตัวอย่าง

def arrayreverse(A, n):
    print("REVERSE OF AN ARRAY UPTO", n, "POSITION:", A[n-1::-1] + A[n:])

if __name__ == "__main__":
    A = []
    n1 = int(input("Enter the size of the List: "))
    print("Enter the Elements:")
    for _ in range(n1):
        A.append(int(input()))
    n = int(input("Enter the position to reverse: "))
    arrayreverse(A, n)

ผลลัพธ์

Enter the size of the List: 6
Enter the Elements:
2
3
4
1
78
23
Enter the position to reverse: 5
REVERSE OF AN ARRAY UPTO 5 POSITION: [78, 1, 4, 3, 2, 23]