用于检查简单括号匹配的 Python 程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38833819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python program to check matching of simple parentheses
提问by Vishesh
I am a Python newbie and I came across this exercise of checking whether or not the simple brackets "(", ")" in a given string are matched evenly.
我是 Python 新手,我遇到了检查给定字符串中的简单括号 "(", ")" 是否均匀匹配的练习。
I have seen examples here using the stack command which I havent encountered yet.So I attempted a different approach. Can anyone tell me where I am going wrong?
我在这里看到过使用我还没有遇到过的 stack 命令的例子。所以我尝试了一种不同的方法。谁能告诉我我哪里出错了?
def matched(str):
ope = []
clo = []
for i in range(0,len(str)):
l = str[i]
if l == "(":
ope = ope + ["("]
else:
if l == ")":
clo = clo + [")"]
else:
return(ope, clo)
if len(ope)==len(clo):
return True
else:
return False
The idea is to pile up "(" and ")" into two separate lists and then compare the length of the lists. I also had another version where I had appended the lists ope and clo with the relevant i which held either ( or ) respectively.
这个想法是将“(”和“)”堆积成两个单独的列表,然后比较列表的长度。我还有另一个版本,其中我将列表 ope 和 clo 附加了相关的 i ,分别包含 ( 或 ) 。
Thanks for your time!
谢谢你的时间!
采纳答案by Henry Prickett-Morgan
A very slightly more elegant way to do this is below. It cleans up the for loop and replaces the lists with a simple counter variable. It also returns false if the counter drops below zero so that matched(")(")
will return False
.
下面是一种稍微更优雅的方法来做到这一点。它清理 for 循环并用一个简单的计数器变量替换列表。如果计数器低于零,它也会返回 false 以便matched(")(")
返回False
。
def matched(str):
count = 0
for i in str:
if i == "(":
count += 1
elif i == ")":
count -= 1
if count < 0:
return False
return count == 0
回答by kreld
This checks whether parentheses are properly matched, not just whether there is an equal number of opening and closing parentheses. We use a list
as a stack and push onto it when we encounter opening parentheses and pop from it when we encounter closing parentheses.
这将检查括号是否正确匹配,而不仅仅是左括号和右括号的数量是否相等。我们将 alist
用作堆栈并在遇到左括号时将其压入栈中,并在遇到右括号时从栈中弹出。
The main problem with your solution is that it only countsthe number of parentheses but does not matchthem. One way of keeping track of the current depth of nesting is by pushing opening parentheses onto a stack and popping them from the stack when we encounter a closing parenthesis.
您的解决方案的主要问题是它只计算括号的数量但不匹配它们。跟踪当前嵌套深度的一种方法是将左括号推入堆栈,并在遇到右括号时将它们从堆栈中弹出。
def do_parentheses_match(input_string):
s = []
balanced = True
index = 0
while index < len(input_string) and balanced:
token = input_string[index]
if token == "(":
s.append(token)
elif token == ")":
if len(s) == 0:
balanced = False
else:
s.pop()
index += 1
return balanced and len(s) == 0
回答by ?ukasz Rogalski
Most blatant error done by you is:
你犯的最明显的错误是:
if l == ")":
clo = clo + [")"]
else:
return(ope, clo) # here
By using return, you exit from function when first char not equal to "(" or ")" is encountered. Also some indentation is off.
通过使用 return,当遇到第一个不等于“(”或“)”的字符时,您退出函数。还有一些缩进关闭。
Minimal change which allows your code to run (although it won'tgive correct answers for all possible input strings) is:
允许您的代码运行的最小更改(尽管它不会为所有可能的输入字符串提供正确答案)是:
def matched(str):
ope = []
clo = []
for i in range(0,len(str)):
l = str[i]
if l == "(":
ope = ope + ["("]
elif l == ")":
clo = clo + [")"]
if len(ope)==len(clo):
return True
else:
return False
回答by Kavitha Madhavaraj
My solution here works for brackets, parentheses & braces
我的解决方案适用于括号、圆括号和大括号
openList = ["[","{","("]
closeList = ["]","}",")"]
def balance(myStr):
stack= []
for i in myStr:
if i in openList:
stack.append(i)
elif i in closeList:
pos = closeList.index(i)
if ((len(stack) > 0) and (openList[pos] == stack[len(stack)-1])):
stack.pop()
else:
return "Unbalanced"
if len(stack) == 0:
return "Balanced"
print balance("{[()](){}}")
回答by Nitheesh MN
this code works fine
这段代码工作正常
def matched(s):
p_list=[]
for i in range(0,len(s)):
if s[i] =='(':
p_list.append('(')
elif s[i] ==')' :
if not p_list:
return False
else:
p_list.pop()
if not p_list:
return True
else:
return False
回答by Rajiv
a = "((a+b)*c)+(b*a))"
li = list(a)
result = []
for i in range(0, len(a)):
if a[i] == "(":
result.append(i)
elif a[i] == ")":
if len(result) > 0:
result.pop()
else:
li.pop(i)
for i in range(0, len(result)):
li.pop(result[i])
print("".join(li))
回答by Teivaz
The problem with your approach is that you don't consider the order. Following line would pass: ))) (((
.
I'd suggest to keep the count of open and closed parenthesis:
您的方法的问题在于您没有考虑订单。以下行将通过:))) (((
. 我建议保留左括号和右括号的数量:
counter
starts from 0- every
(
symbol increment counter - every
)
symbol decrements counter - if at any moment counter is negative it is an error
- if at the end of the line counter is 0 - string has matching parenthesis
counter
从 0 开始- 每个
(
符号增量计数器 - 每个
)
符号递减计数器 - 如果在任何时候计数器为负,则为错误
- 如果在行尾计数器为 0 - 字符串有匹配的括号
回答by Arjun P P
if "(" ,")" these two characters are not present then we don't want to return true or false just return no matching found. if matching found i just checking the count of both characters are same then return true, else return false
如果 "(" ,")" 这两个字符不存在,那么我们不想返回 true 或 false 只返回未找到匹配项。如果找到匹配,我只是检查两个字符的计数是否相同然后返回 true,否则返回 false
def matched(str):
count1=0
count2=1
for i in str:
if i =="(":
count1+=1:
elif i==")":
count2+=1:
else:
print "no matching found for (,)"
if count1==count2:
return True
else:
return False
回答by Belal Iqbal
Simplest of all , though all of you guys have done good:
最简单的,虽然你们都做得很好:
def wellbracketed(s):
left=[]
right=[]
for i in range(0,len(s)):``
if s[i]=='(':
left=left+['(']
elif s[i]==')':
if len(left)!=0:
right=right+[')']
else:
return False
return(len(left)==len(right))
回答by Alain T.
You can do this in a couple of lines using accumulate (from itertools). The idea is to compute a cumulative parenthesis level going through the string with opening parentheses counting as level+1 and closing parentheses counting as level-1. If, at any point, the accumulated level falls below zero then there is an extra closing parenthesis. If the final level is not zero, then there is a missing closing parenthesis:
您可以使用accumulate(来自itertools)在几行中完成此操作。这个想法是计算通过字符串的累积括号级别,左括号计为级别+1,右括号计为级别1。如果在任何时候累积水平低于零,则有一个额外的右括号。如果最终级别不为零,则缺少右括号:
from itertools import accumulate
def matched(s):
levels = list(accumulate((c=="(")-(c==")") for c in s))
return all( level >= 0 for level in levels) and levels[-1] == 0