Python program to check matching of simple parentheses

This checks whether parentheses are properly matched, not just whether there is an equal number of opening and closing parentheses. We use a list as a stack and push onto it when we encounter opening parentheses and pop from it when we encounter closing parentheses.

The main problem with your solution is that it only counts the number of parentheses but does not match them. One way of keeping track of the current depth of nesting is by pushing opening parentheses onto a stack and popping them from the stack when we encounter a closing parenthesis.

def do_parentheses_match(input_string):
    s = []
    balanced = True
    index = 0
    while index < len(input_string) and balanced:
        token = input_string[index]
        if token == "(":
            s.append(token)
        elif token == ")":
            if len(s) == 0:
                balanced = False
            else:
                s.pop()

        index += 1

    return balanced and len(s) == 0

A very slightly more elegant way to do this is below. It cleans up the for loop and replaces the lists with a simple counter variable. It also returns false if the counter drops below zero so that matched(")(") will return False.

def matched(str):
    count = 0
    for i in str:
        if i == "(":
            count += 1
        elif i == ")":
            count -= 1
        if count < 0:
            return False
    return count == 0