Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么这个python函数返回true?_Python - Fatal编程技术网

为什么这个python函数返回true?

为什么这个python函数返回true?,python,Python,我不明白当输入字符串包含匹配括号时,该函数何时返回“True”?它在哪里返回“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:

我不明白当输入字符串包含匹配括号时,该函数何时返回“True”?它在哪里返回“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('[]')

在方法的最后一行,它检查堆栈大小是否为零。如果为0,则表示已处理所有字符,并且没有无效组合,因此返回true。若size为非零,则表示仍有一些圆括号需要与左圆括号匹配,并且方法返回false

当堆栈的长度/大小为零时,len(stack)==0变为真


你也许可以通过简单的练习来回答你自己的问题