Return positions of matching closing parenthesis

def get_closing_paren(sentence, opening_paren_index):
    open_nested_parens = 0
    position = opening_paren_index + 1

    for char in sentence[position:]:
        if char == '(':
            open_nested_parens += 1
        elseif char == ')':
            if open_nested_parens == 0:
                return position
            else:
                open_nested_parens -= 1
        position += 1

    raise Exception("No closing parenthesis :(")

source: https://www.interviewcake.com/question/matching-parens

Leave a Reply

You must be logged in to post a comment.