[英]Parenthesis matching code in python
I have written following code and it was working fine.But One of the case it is failing.I tried but not able to fix this issue. 我写了下面的代码,它工作正常。但其中一个案例是失败。我尝试但无法解决这个问题。
#!/usr/bin/env py
import itertools
import sys
import sympy
import re
import pprint
def extract_next_state(s):
p = re.compile('(\()|(\))')
depth = 0
startindex = None
start_point = False
for m in p.finditer(s):
if m.group(1): # (
depth += 1
print "depth (", depth
if not start_point:
startindex = m.start()
start_point = True
elif m.group(2): # )
depth -= 1
print "depth )", depth
if depth == 0:
return s[startindex:m.end()]
return s[startindex:] + ')' * depth
if __name__ == "__main__":
#data = ['next_state=(~SE&((~B2&D)|(B2&lq))|(SE&SI))']
#data = ['next_state=((~SE&((A1&A2)|(B1&B2)))|(SE&SI)))']
#data = ['next_state=((((~SE&((A1&A2)|(B1&B2)))|(SE&SI)))']
data = ['next_state=(D1&S&!SE)|(!S&(!SE&D0))|(SE&SI))']
data_1 = data[0].split(',')
com = None
for item in data_1:
if item.find('next_state=')!= -1:
item_list = item.split('=')
item_op = extract_next_state(item_list[1])
print item_op
output: 输出:
(D1&S&!SE) (D1&S&!SE)
Expected : 预期:
(D1&S&!SE)|(!S&(!SE&D0))|(SE&SI) (D1&S&SE!)|(S&(SE&D0)!)|(SE&SI)
You checking for depth == 0
as condition for returning from extract_next_state()
. 检查depth == 0
作为从extract_next_state()
返回的条件。 That is extract_next_state()
returns once the matching closing parenthesis to the first opening parenthesis is found. 也就是说, extract_next_state()
找到匹配的右括号到第一个左括号, extract_next_state()
返回。 The rest of the string is then not checked for any further parenthesis of course. 然后,当然不检查字符串的其余部分是否有任何进一步的括号。
It's hard to recommend a solution without knowing what rules for "next_state" or the grammar for allowd expressions. 在不知道“next_state”的规则或允许表达式的语法的情况下,很难推荐解决方案。 But from the last line extract_next_state
it seems you wish to close any open parenthesis. 但是从最后一行extract_next_state
看来你似乎想要关闭任何打开的括号。 So a possible solution may be: 所以可能的解决方案可能是:
def extract_next_state(s):
p = re.compile('(\()|(\))')
depth = 0
startindex = None
endindex = None
for m in p.finditer(s):
if m.group(1): # (
depth += 1
print "depth (", depth
if not startindex:
startindex = m.start()
elif m.group(2): # )
depth -= 1
print "depth )", depth
if depth == 0:
endindex = m.end()
return s[startindex:(endindex if depth == 0 else None)] + ')' * depth
If with the last closing parenthesis all pairs are matched, the rest of the string is discarded, else a matching number of closing parentheses will be added. 如果使用最后一个右括号匹配所有对,则丢弃该字符串的其余部分,否则将添加匹配数量的右括号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.