【发布时间】: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