ที่นี่ให้อาร์เรย์อินพุตของผู้ใช้และตำแหน่งของอาร์เรย์ที่จะย้อนกลับ ดังนั้นงานของเราคือย้อนกลับอาร์เรย์นี้ เราแค่กลับอาร์เรย์ย่อยจาก [0 เป็น (n-1)]
ตัวอย่าง
Input : A=[3, 7, 6, 4, 1, 2] n=4 Output : [1, 4, 6, 7, 3, 2]
อัลกอริทึม
Step 1: reverse list starting from n-1 position. Step 2: split remaining list after n. Step 3: concat both parts and prints
โค้ดตัวอย่าง
#Program to reverse an array
#up to a n position
def arrayreverse(A, n):
#generate list starting from n-1 position element till first element in #reverse order
print ("REVERSE OF AN ARRAY UPTO",n,"POSITION",A[n-1::-1] + A[n:])
# Driver program
if __name__ == "__main__":
A=list()
n1=int(input("Enter the size of the List ::"))
print("Enter the Element of List ::")
for i in range(int(n1)):
k=int(input(""))
A.append(k)
n=int(input("Enter the position to be reverse ::"))
arrayreverse(A, n) ผลลัพธ์
Enter the size of the List :: 6 Enter the Element of List :: 2 3 4 1 78 23 Enter the position to be reverse : 5 REVERSE OF AN ARRAY UPTO 5 POSITION [78, 1, 4, 3, 2, 23]