tha*_*ble 10 python syntax-checking parentheses
我希望能够将所有括号配对成一个字符串,如果它们没有配对,那么它们会得到它们的索引号和False.似乎它一遍又一遍地重复一些值,即cl == pop [1].我试图看看问题出在哪里,但无论我怎么努力,我都看不到它.所以我问是否有人帮助我找到错误,甚至可能改进我的代码;)
def check_parentheses(string):
pending = 0
brackets = []
'''Checks if parens are paired, otherwise they are bad.'''
parenstack = collections.deque()
for ch in string:
if ch in lrmap:
try:
cl = string.index(ch, pending)
pending = cl + 1
except:
cl = False
if ch in lparens:
parenstack.append([ch, cl])
print parenstack
elif ch in rparens:
try:
pop = parenstack.pop()
if lrmap[pop[0]] != ch:
print 'wrong type of parenthesis popped from stack',\
pop[0], ch, pop[1], cl
brackets.append([pop[1], False])
brackets.append([cl, False])
else:
brackets.append([pop[1], cl])
except IndexError:
print 'no opening parenthesis left in stack'
brackets.append([cl, False])
# if we are not out of opening parentheses, we have a mismatch
for p in parenstack:
brackets.append([p[1],False])
return brackets
Run Code Online (Sandbox Code Playgroud)
hug*_*own 20
您可以将我的代码调整为类似的问题:
def Evaluate(str):
stack = []
pushChars, popChars = "<({[", ">)}]"
for c in str :
if c in pushChars :
stack.append(c)
elif c in popChars :
if not len(stack) :
return False
else :
stackTop = stack.pop()
balancingBracket = pushChars[popChars.index(c)]
if stackTop != balancingBracket :
return False
else :
return False
return not len(stack)
Run Code Online (Sandbox Code Playgroud)
iparens = iter('(){}[]<>')
parens = dict(zip(iparens, iparens))
closing = parens.values()
def balanced(astr):
stack = []
for c in astr:
d = parens.get(c, None)
if d:
stack.append(d)
elif c in closing:
if not stack or c != stack.pop():
return False
return not stack
Run Code Online (Sandbox Code Playgroud)
例:
>>> balanced('[1<2>(3)]')
True
>>> balanced('[1<2(>3)]')
False
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
31900 次 |
最近记录: |