简体   繁体   中英

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('[]')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM