简体   繁体   English

比较python中的括号

[英]compare parenthesis in python

from collections import Counter
x = '((()))'

print Counter(x)

Counter({')': 3, '(': 3})

I need to compare whether the open brackets and close brackets of my string are equal or not. 我需要比较我的字符串的方括号和方括号是否相等。 I used counter to do this. 我用计数器来做到这一点。 But how should I compare the two values of the counter variable? 但是如何比较计数器变量的两个值?

You can use a small function which uses .count() : 您可以使用一个使用.count()的小函数:

>>> def checkparen(inp):
...     return inp.count('(') == inp.count(')') and inp.count('[') == inp.count(']') and inp.count('{') == inp.count('}')
... 

As such: 因此:

>>> checkparen('((()))')
True
>>> checkparen('((())')
False
>>> checkparen('[ [ { { ( ( ) ) } } ] ]')
True
>>> 

Or, using collections.Counter : 或者,使用collections.Counter

>>> def checkparen(inp):
...     counter = collections.Counter(inp)
...     symbols = {'{':'}','[':']','(':')'}
...     for symbol in symbols:
...             if counter[symbol] != counter[symbols[symbol]]:
...                     return False
...     return True
... 
>>> checkparen('{')
False
>>> checkparen('[ [ { { ( ( ) ) } } ] ]')
True
>>> 

In general, when you try and extend to the larger problem described in the article you linked, the class of problems you are looking for is context-free-grammar parsers . 通常,当您尝试扩展到所链接文章中描述的较大问题时,您正在寻找的问题类别是上下文无关语法解析器 This is a very classic problem 这是一个非常经典的问题

http://en.wikipedia.org/wiki/Context-free_grammar#Well-formed_nested_parentheses_and_square_brackets http://en.wikipedia.org/wiki/Context-free_grammar#Well-formed_nested_pa​​rentheses_and_square_brackets

even considered canonical as an introduction to compiler theory and related topics. 甚至认为规范是编译器理论和相关主题的简介。

A simple top-down parser is very easy to implement http://effbot.org/zone/simple-top-down-parsing.htm 一个简单的自上而下的解析器很容易实现http://effbot.org/zone/simple-top-down-parsing.htm

A chart parser like Early is tougher, but there are 150 line implementations avaliable https://github.com/tomerfiliba/tau/blob/master/earley3.py 像Early这样的图表解析器比较困难,但是有150种行实现可用https://github.com/tomerfiliba/tau/blob/master/earley3.py

You can also use a parser generator. 您还可以使用解析器生成器。

Any other approach might seem nice at the beginning, but this will be the only strategy that will scale 在开始时,任何其他方法似乎都不错,但这将是唯一可以扩展的策略

I think that you can use a list as a stack to see if all the brackets match, like this: 我认为您可以将列表用作堆栈来查看所有方括号是否匹配,如下所示:

def checkio(expr):
    a_stack = []
    for i in expr:
        if i in '({[':
            a_stack.append(i)
        elif i in '}])':
            if a_stack == []:
                return False
            else:
                poped = a_stack.pop()
                if poped == '(' and i != ')':
                    return False
                elif poped == '[' and i != ']':
                    return False
                elif poped == '{' and i != '}':
                    return False
    return len(a_stack) == 0

print checkio("((5+3)*2+1)") == True
print checkio("{[(3+1)+2]+}") == True
print checkio("(3+{1-1)}") == False
print checkio("[1+1]+(2*2)-{3/3}") == True
print checkio("(({[(((1)-2)+3)-3]/3}-3)") == False
print checkio("2+3") == True

First push a char into a stack, then pop one and see if they are matched, at last too see if the stack is empty. 首先将一个char放入堆栈中,然后弹出一个并查看它们是否匹配,最后还要查看堆栈是否为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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