括号配对 ({}[]()<>) 问题
我希望能够将字符串中的所有括号配对,如果它们没有配对,那么它们会得到索引号和 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您可以将我的代码改编为类似的问题:
You can adapt my code to a similar question:
例子:
Example:
谢谢hughdbrown,你的代码运行起来很轻松,而且非常短!你刚刚让我头疼了 :D
如果可以的话,将其转换为 pep8 :)
编辑
HTML
Python
C++
你明白了吗?:)
Thanks hughdbrown your code was a breeze to get working and it's really short! You've just saved me a headache :D
converted it to pep8 if thats ok :)
Edit
HTML
Python
C++
you get the point? :)
Python 3 中的一个可以理解的解决方案:
An understandable solution in Python 3:
试试这个:
Try this:
下面的代码将显示缺少的括号以及给定字符串中缺少的次数。
The below code will display the missing parentheses and the no of times missing in the given string.
首先,我们将从左到右扫描字符串,每次看到左括号时,我们都会将其推入堆栈,因为我们希望首先关闭最后一个左括号。 (记住堆栈的 FILO 结构!)
然后,当我们看到右括号时,我们通过从堆栈中弹出一个元素来检查最后打开的括号是否是相应的右括号。如果它是有效的匹配,那么我们继续前进,如果不是则返回 false。
代码:
https://gist.github.com/i143code/51962bfb1bd5925f75007d4dcbcf7f55
First we will scan the string from left to right, and every time we see an opening parenthesis we push it to a stack, because we want the last opening parenthesis to be closed first. (Remember the FILO structure of a stack!)
Then, when we see a closing parenthesis we check whether the last opened one is the corresponding closing match, by popping an element from the stack. If it’s a valid match, then we proceed forward, if not return false.
Code:
https://gist.github.com/i143code/51962bfb1bd5925f75007d4dcbcf7f55
我最近的一个项目需要一些东西,并且认为我可以在 OP 的解决方案的基础上进行一些构建。它允许检查注释模式、引号和括号,同时忽略周围的文本。我故意让它变得比需要的更通用,以便其他人可以拿走他们想要的东西,剪掉他们不想要的东西。
I needed something for a recent project and figured I could build on the OP's solution a bit. It allows for comment patterns, quotes and brackets to be checked, whilst ignoring the surrounding text. I've purposefully made it more generic than it needs to be so that others can take what they want and cut out what they don't.