Program to find goal parser interpretation command in Python

Suppose we have a Goal Parser that can interpret a given string command. A command consists of

  • An alphabet "G",

  • Opening and closing parenthesis "()"

  • and/or "(al)" in some order.

Our Goal Parser will interpret "G" as the string "G", "()" as "o", and "(al)" as the string "al". Finally interpreted strings are then concatenated in the original order. So if we have string command, we have to find the Goal Parser's interpretation of command.

So, if the input is like command = "G()()()(al)(al)", then the output will be Goooalal.

To solve this, we will follow these steps −

  • s:= blank string

  • for i in range 0 to size of command - 1, do

    • if command[i] is not same as "(" and command[i] is not same as ")", then

      • s := s concatenate command[i]

    • if command[i] is same as "(" and command[i+1] is same as ")" and i+1<len(command) , then

      • s := s concatenate 'o'

    • if command[i] is same as "(", then

      • go for next iteration

    • if command[i] is same as ")", then

      • go for next iteration

  • return s

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(command):
   for i in range(len(command)):
      if command[i]!="(" and command[i]!=")":
      if command[i]=="(" and command[i+1]==")" and i+1<len(command):
      if command[i]=="(":
      if command[i]==")":
   return s

command = "G()()()(al)(al)"





Updated on: 18-May-2021


Kickstart Your Career

Get certified by completing the course

Get Started