1

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?

1 Answer 1

3

command.index() gives you the first occurrence of '('.

Rewrite your function as follows:

def interpret(command: str) -> str:

    res = ""

    for c, i in enumerate(command):

        if i == "G":
            res += i

        if i == "(":
            ind = c
            if command[ind + 1] == ")":
                res += "o"
            if command[ind + 1] == "a":
                res += "al"

    return res
Sign up to request clarification or add additional context in comments.

2 Comments

Note: It's really weird to name the index c and the value i; i is almost always the name of the index. I realize the OP used i for the value, but ugh, don't encourage that.
Ohhh now that makes perfect sense! Thanks mate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.