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

โปรแกรม Python อัลกอริทึมกลับลำดับสำหรับการหมุนอาร์เรย์


เมื่อต้องการกลับลำดับอาร์เรย์ที่หมุนแล้ว กำหนดเมธอดที่วนลูปผ่านลิสต์และกลับลำดับลิสต์ อีกเมธอดหนึ่งหมุนลิสต์ และอีกเมธอดแสดงลิสต์ ใช้ลูปและ indexing ธรรมดา

ตัวอย่าง

def reverse_list(my_list, begin, end):
    while begin < end:
        temp = my_list[begin]
        my_list[begin] = my_list[end]
        my_list[end] = temp
        begin += 1
        end = end - 1

def left_rotate(my_list, to_rotate):
    n = len(my_list)
    reverse_list(my_list, 0, to_rotate - 1)
    reverse_list(my_list, to_rotate, n - 1)
    reverse_list(my_list, 0, n - 1)

def print_it(my_list):
    for i in range(0, len(my_list)):
        print(my_list[i])

my_list = [34, 42, 56, 78, 9, 0, 23]
print("The list is :")
print(my_list)
print("The left_rotate method is being called")
left_rotate(my_list, 3)
print("The list after rotation is : ")
print_it(my_list)

ผลลัพธ์

The list is : [34, 42, 56, 78, 9, 0, 23]
The left_rotate method is being called
The list after rotation is : 78 9 0 23 34 42 56

คำอธิบาย

  • กำหนดเมธอด 'reverse_list' กลับลำดับลิสต์ที่กำหนด
  • กำหนดเมธอด 'rotate_list' หมุนลิสต์ตามค่า pivot เฉพาะ
  • กำหนดเมธอด 'print_it' พิมพ์ลิสต์บนคอนโซล
  • กำหนดลิสต์ และแสดงบนคอนโซล
  • เรียกเมธอด 'left_rotate' บนลิสต์นี้ และแสดงองค์ประกอบหลังหมุนและกลับลำดับ