So I was trying to solve this leetcode problem:
Input: command = "G()(al)"
Output: "Goal"
Explanation: The Goal Parser interprets the command as follows:
G -> G
() -> o
(al) -> al
The final concatenated result is "Goal".
This is my code:
def interpret(command: str) -> str:
res = ''
for i in command:
if i == 'G':
res += i
if i == '(':
ind = command.index(i)
if command[ind + 1] == ')':
res += 'o'
if command[ind + 1] == 'a':
res += 'al'
return res
The problem is, instead of returning 'Goal', the function returns 'Goo'. So I changed the function to the following to see what's going on:
for i in command:
if i == '(':
print(command.index(i))
And the above code prints out this
1
1
which means the loop is iterating an element twice?
What did I do wrong and how can I fix the function to return the correct output?