简体   繁体   English

平衡括号挑战:检查不包含括号的字符串

[英]Balanced Parenthesis challenge: Checking for string that contains no parenthesis

I did an implementation on checking if whether a string has balanced parentheses or not using a STACK only. 我进行了一个检查字符串是否带有平衡括号的实现,而不是仅使用STACK。 But I checked for balanced parentheses when the string has words. 但是当字符串中有单词时,我检查了括号是否平衡。 For example: 例如:

>>> is_paren_balanced("[{whoa (this is rough [how do I do this!])}]")
True

I was successful in doing that. 我成功地做到了。 However, I am not trying to check for a case if the string has NO parenthesis. 但是,我没有尝试检查字符串是否没有括号的情况。 And then i got this result: 然后我得到了这个结果:

>>> is_paren_balanced("Hi i love food.")
no parenthesis
True
>>> is_paren_balanced("[{whoa (this is rough [how do I do this!])}]")
no parenthesis
False

For the first result, I don't want the boolean result as thats kind of vague. 对于第一个结果,我不希望布尔结果那样模糊。 I'm trying to show the user that the string has no parenthesis so it is neither True or False. 我试图向用户显示该字符串没有括号,因此它既不是True也不是False。 I just want the print statement shown saying "no parentheses here" or whatever. 我只想要显示的打印语句说“这里没有括号”或其他内容。 For the second result, obviously just the boolean result and it shouldve returned True. 对于第二个结果,显然只是布尔结果,它应该返回True。

Any suggestions? 有什么建议么? I'm stumped. 我很沮丧

Here is the code I'm practicing with: 这是我正在练习的代码:

from stack import Stack

def is_match(p1, p2):
    if p1 == "(" and p2 == ")":
        return True

    elif p1 == "{" and p2 == "}":
        return True

    elif p1 == "[" and p2 == "]":
        return True

    else:
        return False


def is_paren_balanced(paren_str):
    s = Stack() #initialize a stack object
    is_balanced = True #boolean flag: whether the str has balanced parenthesis or not
    # then set to false if otherwise
    index = 0 # keep track of where we are in the string
    paren_str = paren_str.replace(" ", "") #accounts for possible spaces in the input


    while index < len(paren_str) and is_balanced:
        paren = paren_str[index]       
        if paren in "({[":
            s.push(paren)

        elif paren in ")}]":
            if s.is_empty():
                is_balanced = False

            else:
                top = s.pop()
                if not is_match(top, paren):
                    is_balanced = False

        else:
            if paren not in "({[]})":
                print("no parenthesis")
                break



        index += 1

    if s.is_empty() and is_balanced:
        return True

    else:
        return False

Sorry if it doesn't seem pythonic. 抱歉,如果它看起来不是pythonic。 I was just mostly exploring with this problem and will edit and improve later on. 我只是在探索这个问题,以后会进行编辑和改进。

You can use either regex or list comprehension to get the total amount of parenthesis first: 您可以使用正则表达式或列表理解来首先获取括号的总数:

import re

def all_parenthesis(msg):
    left = re.findall(r"[\[{(]",msg)
    right = re.findall(r"[\]|})]",msg)
    if not left and not right:
        return "No parenthesis"
#or

def check_balance(msg):
    d = {"[":"]",
         "{":"}",
         "(":")"}
    left = [char for char in msg if char in d]
    right = [char for char in reversed(msg) if char in d.values()]  
    #if not left not right...  

But if you already constructed a list of parenthesis on both sides, why don't go ahead and compare them instead? 但是,如果您已经在两边都构造了一个括号列表,为什么不继续进行比较呢? Could be something like this: 可能是这样的:

def check_balance(msg):
    d = {"[":"]",
         "{":"}",
         "(":")"}
    left = [char for char in msg if char in d]
    right = [char for char in reversed(msg) if char in d.values()]
    if not left and not right:
        return "No parenthesis"
    elif len(left) != len(right):
        return False
    for a, b in zip(left,right):
        if d.get(a) != b:
            return False
    return True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM