问题描述
我需要使用堆栈来检查用户输入中是否存在任何不平衡的括号。代码的逻辑应该使用 stack 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 从堆栈中删除左括号。我觉得堆栈应该是空的代码输出平衡括号和 unempty 输出不平衡括号。代码如下
##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()))
我也觉得我应该只使用一个列表来扫描字符串中的 "("
将它们添加到列表中,扫描相反的语法 ")"
并对它们的长度进行一些比较。>
解决方法
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 的计数器变量。现在迭代用户字符串,并在每个 (
do counter++
& 在每个 )
do counter--
。
在任何迭代 counter < 0
时中断。
现在在循环外,如果counter==0
,则其有效否则无效。
示例代码:
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")
,
你可以试试下面的代码
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
这个想法很简单,继续将左边的对应物推入堆栈,一旦在表达式中遇到右边的对应物,就弹出堆栈,看看它是否是该方括号/花括号/圆括号对应的右边对应物。
最后,如果你的堆栈是空的,这意味着你的表达是平衡的。