用于检查简单括号匹配的Python程序

时间:2016-08-08 16:03:36

标签: python

我是一名Python新手,我遇到了检查简单括号"(",")"在给定的字符串中均匀匹配。

我在这里看到了使用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

这个想法是堆积起来"("和")"分成两个单独的列表,然后比较列表的长度。我还有另一个版本,其中我附加了列表ope和clo与相关的i分别持有(或)。

谢谢你的时间!

29 个答案:

答案 0 :(得分:8)

下面是一个非常优雅的方法。它清理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

答案 1 :(得分:6)

检查括号是否正确匹配,而不仅仅是是否有相同数量的左括号和右括号。我们使用list作为堆栈,当我们遇到左括号时将它推到它上面,当我们遇到右括号时从它弹出。

您的解决方案的主要问题是它只计算括号的数量但不匹配它们。跟踪当前嵌套深度的一种方法是将开括号推入堆栈,并在遇到右括号时从堆栈中弹出它们。

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

答案 2 :(得分:5)

你做的最明显的错误是:

    if l == ")":
        clo = clo  + [")"]
    else:
        return(ope, clo)  # here

通过使用return,当遇到第一个char不等于“(”或“)”时,退出函数。还有一些缩进。

允许代码运行的最小更改(尽管不会为所有可能的输入字符串提供正确的答案)是:

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

答案 3 :(得分:4)

我的解决方案适用于括号,括号和&amp;大括号

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("{[()](){}}") 

答案 4 :(得分:3)

此代码可以正常使用

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

答案 5 :(得分:2)

您的方法存在的问题是您不考虑订单。以下行将通过:))) (((。 我建议保持开括号和闭括号的计数:

  • counter从0
  • 开始
  • 每个(符号增量计数器
  • 每个)符号递减计数器
  • 如果在任何时刻计数器为负数则为错误
  • 如果在行计数器的末尾是0 - 字符串具有匹配的括号

答案 6 :(得分:2)

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))

答案 7 :(得分:1)

最简单的,尽管你们所有人都做得很好:

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))

答案 8 :(得分:1)

这是通过一个计数器来解决它的另一种方法,该计数器跟踪在这个时刻有多少开放括号。 这应该照顾所有的情况。

def matched(str):
    diffCounter = 0
    length = len(str)
    for i in range(length):
        if str[i] == '(':
            diffCounter += 1
        elif str[i] == ')':
            diffCounter -= 1
    if diffCounter == 0:
        return True
    else:
        return False

答案 9 :(得分:1)

如果&#34;(&#34;,&#34;)&#34;这两个字符不存在然后我们不想返回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

答案 10 :(得分:0)

您可以检查此代码。
此代码不使用堆栈操作。

def matched(s):
  count = 0
  for i in s:
    if i is "(":
      count += 1
    elif i is ")":
      if count != 0:
        count -= 1
      else:
        return (False)

  if count == 0:
    return (True)
  else:
    return (False)

答案 11 :(得分:0)

给定一个只包含字符 '(', ')', '{', '}', '[' 和 ']' 的字符串 s, 判断输入字符串是否有效。

def isValid(s):
    stack = []
    for i in s:
        if i in open_list:
            stack.append(i)
        elif i in close_list:
            pos = close_list.index(i)
            if open_list[pos] == stack[len(stack)-1]:
                stack.pop()
            else:
                return False
    if len(stack) == 0:
        return True
    else:
        return False

print(isValid("{[(){}]}"))

答案 12 :(得分:0)

def matched(str):
    braces = {"{": "}", "(": ")", "[": "]"}
    stack = []
    for c in str:
        if c in braces.keys():
            stack.append(c)
        elif c in braces.values():
            if not stack:
                return False
            last_brace = stack.pop()
            if braces[last_brace] != c:
                return False
    if stack:
        return False
    return True

print(matched("()"))
>> True
print(matched("(}"))
>> False
print(matched("}{"))
>> False
print(matched("}"))
>> False
print(matched("{"))
>> False
print(matched("(ff{fgg} [gg]h)"))
>> True

答案 13 :(得分:0)

理解这个片段的最好方法是跟随各种场景。

self.filteredContacts = contacts.flatMap(\.1) // for older swift syntax you can use `flatMap { $1 }`

答案 14 :(得分:0)

只是稍微修改了亨利·普里克特-摩根(Henry Prickett-Morgan)的代码,以更合理地处理它,即考虑到“(”的数目与“)”的数目匹配,但字符串以“)”开头或以“(”结束)显然是不对的。


def ValidParenthesis(s):
    count = 0
    if s[0] == ')' or s[-1] == '(':
      return False
    else:
      for c in s:
        if c == '(':
          count += 1
        elif c == ')':
          count -= 1
        else:
          continue
      return count == 0

答案 15 :(得分:0)

有点不同。

expression = '{(){({)}}'
brackets = '[](){}'
stack  = []
balanced = False
for e in expression:
    if e in brackets and stack: # Popping from the stack if it is closing bracket
        if stack [-1] == brackets[brackets.index(e)-1]:
            stack.pop()
            balanced = True
            continue # it will go to the new iteration skipping the next if below
    if e in brackets: # Push to stack if new bracket in the expression
        stack .append(e)
        balanced = False
balanced = 'Balanced' if balanced and not stack  else 'Unbalanced'
print(balanced, stack)

答案 16 :(得分:0)

检查平衡嵌套括号的一种替代方法:

def is_balanced(query: str) -> bool:
    # Alternative: re.sub(r"[^()]", "", query)
    query = "".join(i for i in query if i in {"(", ")"})
    while "()" in query:
        query = query.replace("()", "")
    return not query


for stmt in [
    "(()()()())",    # True
    "(((())))",      # True
    "(()((())()))",  # True
    "((((((())",     # False
    "()))",          # False
    "(()()))(()",    # False
    "foo",           # True
    "a or (b and (c or d)",  # False
    "a or (b and (c or d))"  # True
    "a or (b and (c or (d and e)))",  # True
]:
    print(stmt)
    print("Balanced:", is_balanced(stmt))
    print()

它的工作原理是:

  1. 删除除括号外的所有内容
  2. 递归删除最里面的括号对
  3. 如果您除了空字符串之外还剩下任何其他内容,则该语句不平衡。否则,是。

答案 17 :(得分:0)

您可以使用accumulate(来自itertools)在一行中完成此操作。这个想法是要计算通过字符串的累计括号级别,其中左括号的级别为+1,闭括号的级别为-1。如果在任何时候累计水平降到零以下,则表示不匹配:

from itertools import accumulate
def matched(s):
   return not any( level < 0 for level in accumulate((c=="(")-(c==")") for c in s))

答案 18 :(得分:0)

parenthesis_String = input("Enter your parenthesis string")
parenthesis_List = []
for p in parenthesis_String:
    parenthesis_List.append(p)
print(parenthesis_List)

if len(parenthesis_List)%2 != 0:
    print("Not Balanced Wrong number of input")

for p1 in parenthesis_List:
    last_parenthesis = parenthesis_List.pop()
    print(last_parenthesis)
    if (p1 == '{' and last_parenthesis == '}' or p1 == '[' and last_parenthesis == ']' or p1 == '(' and last_parenthesis == ')'):
        print("Balanced")
    else:
        print("Not balanced")

答案 19 :(得分:0)

rect

答案 20 :(得分:0)

更高级的示例,其中您还需要检查方括号的匹配&#39; []&#39;和牙套&#39; {}&#39;收杆。

string = '([]{})'

def group_match(string):

    d = {
    ')':'(',
    ']':'[',
    '}':'{'
    }

    list_ = []

    for index, item in enumerate(string):
        if item in d.values():
            list_.append(item)

        elif (item in d.keys()) and (d.get(item) in list_):
            list_.pop()

    return len(list_) == 0

答案 21 :(得分:0)

最简单的代码!!

def checkpar(x):
    while len(''.join([e for e in x if e in "()"]).split('()'))>1: x=''.join(x.split('()'))
    return not x

答案 22 :(得分:0)

您可能想尝试一下:

def balance_check_new(s):
 if len(s) %2 !=0:
    return False
 exists = set('([{')
 matches = ([('(',')'),('[',']'),('{','}')])
 stack = []
 for paren in s:
    if paren in exists:
        stack.append(paren)
    else:
        if len(stack) == 0:
            return False
        last_open = stack.pop()
        if (last_open,paren) not in matches:
            return False
 return len(stack) == 0

答案 23 :(得分:0)

def parenthesis_check(parenthesis):
    chars = []
    matches = {')':'(',']':'[','}':'{'}
    for i in parenthesis:
        if i in matches:
            if chars.pop() != matches[i]:
                return False
        else:
            chars.append(i)
    return chars == []        

答案 24 :(得分:0)

如果括号序列不是问题(像)(这样的字符串),则此代码更快:

def matched_parenthesis(s):
    return s.count('(') == s.count(')')

用15KB的字符串测试,它是~20μsv。 1ms迭代整个字符串。

对我而言,订单不是问题,因为基础协议保证字符串格式正确。

答案 25 :(得分:0)

如果你还需要从左边找到第一个不匹配支架的位置你可以使用下面的代码,它也涵盖了某些边缘情况:

def isBalanced(expr):
    opening=set('([{')
    new=set(')]}{[(')
    match=set([ ('(',')'), ('[',']'), ('{','}') ])
    stack=[]
    stackcount=[]
    for i,char in enumerate(expr,1):
        if char not in new:
            continue
        elif char in opening:
            stack.append(char)
            stackcount.append(i)
        else:
            if len(stack)==0:
                print(i)
                return False
            lastOpen=stack.pop()
            lastindex=stackcount.pop()
            if (lastOpen, char) not in match:
                print (i)
                return False
    length=len(stack)
    if length!=0:
      elem=stackcount[0]
      print (elem)
    return length==0
string =input()
ans=isBalanced(string)
if ans==True:
    print("Success")

答案 26 :(得分:0)

input_str = "{[()](){}}"
strblance=""

for i in input_str:

    if not strblance:
        strblance = strblance+i
    elif (i is '}' and strblance[len(strblance)-1] is '{') \
        or ( i is']'and strblance[len(strblance)-1] is '[') \
        or ( i is ')'and strblance[len(strblance)-1] is '('):
            strblance = strblance[:len(strblance)-1]
    else:
        strblance = strblance+i

if not strblance:

    print ("balanced")

else:

    print ("Not balanced")

答案 27 :(得分:-1)

foo1="()()())("  

def bracket(foo1):
    count = 0
    for i in foo1:
        if i == "(":
           count += 1
        else:
           if count==0 and i ==")":
               return False
           count -= 1

   if count == 0:
       return True
   else:
       return False

bracket(foo1)

答案 28 :(得分:-1)

虽然我没有提出修复您的实现,但我建议使用更清晰,更pythonic版本的@kreld解决方案:

def check_parentheses(expr):
    s = []
    for c in expr:
        if c in '(':
            s.append(c)
        elif c in ')':
            if not len(s):
                break
            else:
                s.pop()
    else:
        return not len(s)
    return False

# test -----------------------------------------------------------------
test_expr = [')(', '(()', '())', '(', ')', '((', '))', '(()())', '(())',
             '()', '()(())']
for i, t in enumerate(test_expr, 1):
    print '%i\t%s\t%s' % (i, t, check_parentheses(t))

# output ---------------------------------------------------------------
1       )(      False
2       (()     False
3       ())     False
4       (       False
5       )       False
6       ((      False
7       ))      False
8       (()())  True
9       (())    True
10      ()      True
11      ()(())  True