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

โปรแกรม Goal Parser Interpretation ใน Python

โจทย์

Goal Parser แปลคำสั่ง:

  • G → G
  • () → o
  • (al) → al
ต่อผลลัพธ์ตามลำดับ

ตัวอย่าง: command = "G()()()(al)(al)" → Output: "Goooalal"

อัลกอริธึม

  1. วนอ่านตัวอักษร
  2. ถ้า G → เพิ่ม G
  3. ถ้า ( ตามด้วย ) → เพิ่ม o
  4. ถ้า (al) → เพิ่ม al (ข้ามวงเล็บ)

โค้ด Python


def solve(command):
    s = ""
    i = 0
    while i < len(command):
        if command[i] == 'G':
            s += 'G'
            i += 1
        elif command[i] == '(':
            if i + 1 < len(command) and command[i+1] == ')':
                s += 'o'
                i += 2
            else:  # (al)
                s += 'al'
                i += 4
        else:
            i += 1
    return s

command = "G()()()(al)(al)"
print(solve(command))  # Output: Goooalal

Input / Output

Input:  "G()()()(al)(al)"
Output: Goooalal