1

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('[]')
1
  • you might be able to answer your own question by just running it through pythontutor Commented Dec 18, 2016 at 0:23

1 Answer 1

2

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

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

Comments

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.