【问题标题】:Use stack to check for any unbalanced paranthesis on user input in Python使用堆栈检查 Python 中用户输入的任何不平衡括号
【发布时间】:2021-04-05 09:42:32
【问题描述】:

需要使用堆栈来检查用户输入中的任何不平衡括号。代码的逻辑应该使用堆栈push 方法在堆栈中添加一个左括号,并在遇到右括号时将其弹出。当左括号和右括号不平衡时,代码应该中断并打印parenthesis unbalanced。 我试图用这段代码作弊,但最后一个测试用例让我失望了

mytext="))((("#this string input is just sample, the real input is captured from user
if(mytext.count(")")!=mytext.count("(")):
    print("The paranthesis are not balanced")
else:
    print("The parenthesis are balanced")

所以决定用它的方法构建一个堆栈类,坚持捕获左括号"("并将其添加到堆栈中,然后扫描输入以查找右括号")",然后调用pop从堆栈中卸下开口支架。我觉得堆栈对于输出平衡括号的代码应该是空的,对于输出不平衡括号的代码应该是非空的。代码如下

##First you need to create a stack class
class Stack:
    def __init__(self):
        self.items=[]
    def is_empty(self):
        return self.items==[]
    def push(self,item):
        self.items.insert(0,item)
    def pop(self):
        self.items.pop()#removes last element added
    def print_stack(self):#print function for debugging
        print(self.items)







def balanced(expression):#This function checks whether input from user has balanced parenthesis
    #create a stack object
     mystack=Stack()
    #scan user input for opening bracket and add to stack
    #I need help from this point onwards
    if "(" in expression:#if opening bracket exists in input, i feel like i should iterate through the expression
       mystack.push(0,"(")
    if ")" in expression:#remove the previously added opening bracket
       mystack.pop(0):
     ##implement empty_check and return accordingly
        
print(balanced(input()))

我也觉得我应该只使用一个列表从字符串中扫描"(",将它们添加到列表中,扫描相反的语法")",然后对它们的长度进行一些比较。

【问题讨论】:

  • 不,只需从左到右扫描字符串并在遇到 ( ) 时推送/弹出
  • 你能发布代码吗?,请:))
  • 你的想法不错。您只需要在每个字符的循环中进行这些检查,而不是检查 in

标签: python parentheses


【解决方案1】:

你可以试试下面的代码

def check_paranthesis(data):
    stack = []
    pairs = {
        '}': '{',
        ']': '[',
        ')': '('
    }
    for i in data:
        if i in ('(', '[', '{'):
            stack.append(i)
        elif not stack or pairs[i] != stack.pop():
            return False
    
if stack:
        return False
return True


print(check_paranthesis('[()]'))    # True
print(check_paranthesis('[({})]')) # True
print(check_paranthesis('[(})}]'))  # False
print(check_paranthesis('[(])'))  # False
print(check_paranthesis('[()'))  # False
print(check_paranthesis('[(]'))  # False
print(check_paranthesis(']['))  # False
print(check_paranthesis('[['))  # False

这个想法很简单,继续将左侧对应物压入堆栈,一旦在表达式中遇到右侧对应物,弹出堆栈并查看它是否是该括号/花括号/括号对应的右侧对应物。

最后,如果您的堆栈为空,则表示您的表达式是平衡的。

【讨论】:

  • 你可以修改为只检查这些类型的括号"("
  • 你的意思是一个左括号,如果是,那么它也适用于这个print(check_paranthesis('(')). # False。
  • 这个呢`)))))('
  • 您需要在stack.pop() 之前进行下溢检查(并且不需要第一个 if)。
【解决方案2】:
mytext="))((("#this string input is just sample, the real input is captured from user
if(mytext.count(")")!=mytext.count("(")):
    print("The paranthesis are not balanced")
else:
    print("The parenthesis are balanced")

它失败的原因之一是它没有检查 - ) 不应该出现在 ( 之前。

您可以使用的一种简单方法是,创建一个初始值为 0 的计数器变量。现在遍历用户字符串并在每个 ( 上执行 counter++ 和在每个 ) 上执行 counter--。

如果在任何迭代中中断counter < 0。

现在在循环之外,如果counter==0,它的有效else无效。


示例代码:

mytext="((()()))"

ctr = 0
for c in mytext:
    if c == ')':
        ctr -= 1
    elif c == '(':
        ctr += 1
    print("c={}, ctr={}".format(c,ctr))
    if ctr < 0:
        break
if ctr == 0:
    print("Valid")
else:
    print("Not valid")

【讨论】:

  • 代码通过了 7 个测试用例,最后一个测试用例失败了,也就是第八个,让我应用你建议的更改
  • 如果您只是在答案中发布代码和建议会更容易
  • @Source_Code_001 当然,之前没有适当的系统访问权限。
猜你喜欢
  • 2017-06-10
  • 2016-06-26
  • 2016-09-06
  • 1970-01-01
  • 2018-04-23
  • 1970-01-01
  • 2022-01-02
  • 2021-11-30
  • 2020-08-09
相关资源
最近更新 更多