python - 递归匹配括号

标签 python

我编写了下面的递归代码来匹配括号。在某些情况下,我得到“True”,但如果我在字符串中的某个位置添加新的括号(这是不正确的),我仍然得到“True”。我调试了它,但我不明白如何修复它,我该如何纠正它?

def is_balanced(parenthesis):
    if len(parenthesis) %2 == 1:
        return False
        left_value = parenthesis[:1:]
        right_value = parenthesis[-1::]
        return is_balanced(parenthesis[1:-1:]) if left_value != right_value else 
        True

    print(is_balanced('(()()[]()())')) => #True
    print(is_balanced('(()()[[()())')) => #still True

最佳答案

这是一个相当简洁的基于正则表达式的实现:

import re

def is_balanced(par):
    pattern = re.compile('\(\)|{}|\[\]')  # matches '()', '[]', or '{}'
    return not par or bool(pattern.search(par)) and is_balanced(pattern.sub('', par))

关于python - 递归匹配括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53336071/

相关文章:

python - 如何从模型返回自定义 JSON?

python - 将数据插入 Pandas DataFrame 中,无需索引或列开销(因此无需连接或追加)

python - "cannot concatenate ' str ' and ' int ' objects"错误

Python 无法解码 key 大于 127 的异或字符串

python - 为什么要实现两个如此相似的数据结构,如 List 和 Tuple

Python UTF8 编码

python - 如何在 Google Colaboratory 中以编程方式清除 Python 输出?

python - 在 Keras 中下载 ResNet50 生成 "SSL: CERTIFICATE_VERIFY_FAILED"

python - 使用 ipython 调试时记住断点

python - 在Python中从特定DNS服务器解析IP