检查for循环python中的多个项目

时间:2017-03-08 20:27:02

标签: python loops

我写了一个代码告诉用户他们的括号不平衡。

我可以准确地告诉我的代码出错了。

一旦遇到括号的第一种情况,它就不会继续寻找错误的或其他正确的(我认为)。

我想保持简单但很长(即现在没有花哨的快捷方式)

这是我的代码

def isbalanced(text):
    openingbracket=[]
    for i, next in enumerate (text):
        if next=='(' or next=='{' or next=='[':
            openingbracket.append(next)
        if next==')' or next=='}' or next==']':
            if len(openingbracket)==0:
                print("ops only opening brackets")
                return False
            else:
                a=openingbracket.pop()
                if a =='(' and next==')':
                    print("its matched parenthesis")
                    return True
                if a =='{' and next=='}':
                    print("its matched curly brackets")
                    return True
                if a =='[' and next==']':
                    print("its matched square")
                    return True
                else:
                    print("wrong closing brackets")
                    return False
    if len(openingbracket):
        print ("no closing brackets")
        return False
    else:
        print("no brackets")
        return True
isbalanced("Hello()(]")

2 个答案:

答案 0 :(得分:2)

如果您return只要一切正常,您就不会在字符串中找到更多错误......这正是您在3个地方所做的事情:

if a =='(' and next==')':
    print("its matched parenthesis")
    return True  # let it continue to check the string.

在方法的最后添加一个return True:如果循环通过,那么字符串就可以了(实际上它在当前代码中已经没问题了)

除了:

  • 不要将next用于您的变量,因为它是内置的,以便从迭代中获取值。我将使用c
  • if next=='(' or next=='{' or next=='[':可以替换为if c in "({[":
  • for i, next in enumerate (text):您未使用该索引,只需执行for c in text:

答案 1 :(得分:0)

只需删除return True语句,因为在检查字符串的其余部分之前,这些语句会导致整个方法返回True。只有当您处理完整个字符串后,才知道您可以返回True,因此唯一的return True应该在您的for循环完成之后。

def isbalanced(text):
    openingbracket=[]
    for i, next in enumerate (text):
        if next=='(' or next=='{' or next=='[':
            openingbracket.append(next)
        if next==')' or next=='}' or next==']':
            if len(openingbracket)==0:
                print("ops only opening brackets")
                return False
            else:
                a=openingbracket.pop()
                if a =='(' and next==')':
                    print("its matched parenthesis")
                    return True                     # REMOVE THIS LINE
                if a =='{' and next=='}':
                    print("its matched curly brackets")
                    return True                     # REMOVE THIS LINE
                if a =='[' and next==']':
                    print("its matched square")
                    return True                     # REMOVE THIS LINE
                else:
                    print("wrong closing brackets")
                    return False
    if len(openingbracket):
        print ("no closing brackets")
        return False
    else:
        print("no brackets")
        return True
isbalanced("Hello()(]")