Search code examples
pythonstackstructure

What is going on with this balanced paren problem? getting no results and no error


I'm not getting any error or any results so I can't quite pinpoint the issues. It's based on the 'stack' data structure.

def is_match(p1, p2):
    return (p1,p2) in ['(,)', '{,}', '[,]']

def is_open(param):
    return param in '([{'

def is_balanced(exp):
    stack = []
    for i in range(len(exp)):
        if is_open(exp[i]):
            stack.append(exp[i])
        else:
            top = stack.pop()
            if not is_match(top,str(exp[i])):
                return False

    if stack == []:
        return True
    else:
        return False


is_balanced('{[}')

Solution

  • First of all, you are not printing anything. Your function always returns False, but without a print, the result is discarded.

    Secondly, you have logic errors. The most obvious one is ('(', ')') is never equal to '(,)'. And if you don't test if the stack is empty as you pop, so in case of input such as '}', you will get an error. And str(exp[i]) is redundant, exp[i] is a string already. Finally,

    if condition:
        return True
    else:
        return False
    

    is an antipattern; you can simply say return condition (or, if it is not a boolean and you want it to be, return bool(condition); not needed in this case, as the result of equality comparison is always a boolean).