Peter Chao
Peter Chao

Reputation: 443

why this python function return true?

I donot understand when this function will return 'True' when an input string has match parenthesis? Where does it return the 'True'?

def balance_check(s):
    if len(s)%2 !=0:
        return False
    opening = set('([{')
    matches = set([('(',')'),('[',']'),('{','}')] )
    stack =[]
    for paren in s:
        if paren in opening:
            stack.append(paren)
        else:
            if len(stack) == 0:
                return False
            last_open = stack.pop()
            if (last_open,paren) not in matches:
                return False
    return len(stack) == 0


res=balance_check('[]')

Upvotes: 1

Views: 83

Answers (1)

xitter
xitter

Reputation: 768

In the last line of method it checks if stack size is zero. If it is 0, it indicate that all characters have been processed and there is no invalid combination, so it returns true. If size is non-zero, it means some parenthesis is still left to be matched with an opening parenthesis and method return false.

len(stack) == 0 becomes true when length/size of stack is zero

Upvotes: 2

Related Questions