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

โปรแกรมรีเซ็ตพอลิгонสู่สถานะเริ่มต้นใน Python

มีพอลิгон n ด้าน มีแกนพลิก n แกน และจุดหมุน n จุด กำหนดลำดับการหมุนและพลิก (1 หมุน, 2 พลิก) พร้อมแกน k ต้องการหาการดำเนินการเพิ่มเติมหนึ่งขั้นตอน เพื่อให้พอลิゴนกลับสู่สถานะเริ่มต้น

ตัวอย่าง: n=6, input_list=[[1,2],[1,4],[2,3],[2,5],[1,6]] → ผลลัพธ์ (1,4)

ขั้นตอนการแก้ปัญหา

  1. เก็บสถานะ: decision_var (True/False สำหรับการพลิก) และ position (ตำแหน่งการหมุน)
  2. ประมวลผลแต่ละคำสั่ง:
    • หมุน (1): position += y
    • พลิก (2): position = y - position, decision_var = not decision_var
  3. หลังจบ: position %= n
  4. หาก decision_var เป็น True คืนค่า (2, position) มิฉะนั้นคืนค่า (1, n - position)

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

def solve(n, input_list):
    decision_var = False
    position = 0
    for item in input_list:
        x, y = item[0], item[1]
        if x == 1:
            position += y
        else:
            position = y - position
            decision_var = not decision_var
    position %= n
    if decision_var:
        return (2, position)
    else:
        return (1, n - position)

# ทดสอบ
print(solve(6, [[1, 2], [1, 4], [2, 3], [2, 5], [1, 6]]))  # ผลลัพธ์: (1, 4)

อินพุตตัวอย่าง

6, [[1, 2], [1, 4], [2, 3], [2, 5], [1, 6]]

เอาต์พุตตัวอย่าง

(1, 4)