I am doing my lab homework for python and I am stuck on one of the questions. Any help would be greatly appreciated.
我正在为python做我的实验室作业,我仍然坚持其中一个问题。任何帮助将不胜感激。
So the task is to find whether a string has balanced brackets or not. This means that each closing bracket should be in order.
因此,任务是查找字符串是否具有平衡括号。这意味着每个结束括号应该是有序的。
Balanced bracket example:
平衡支架示例:
(<>){}
Unbalanced bracket example:
不平衡支架示例:
())
(<)> (this one is mistmatched)
)(<>
The part I am stuck on is; how can I return the last element of the stack to compare?
我坚持的部分是;如何返回堆栈的最后一个元素进行比较?
def balanced_brackets(text):
s = Stack()
opening_bracket_list = ["(", "[", "{"]
closing_bracket_dict = {")":"(", "]" : "[", "}" : "{"}
text_list = list(text)
for element in text_list:
if element in opening_bracket_list:
s.push(element)
if element in closing_bracket_dict:
if (last element of the stack) == closing_bracket_dict[element]:
s.pop()
else:
return False
if s == []:
return True
As you can see, I split the text into a string and use a for loop. If its an opening bracket, I push it into the stack, if its a closing element, I check if the last element of the stack matches the value from the dictionary. If no it return False
, if yes it returns True
.
如您所见,我将文本拆分为字符串并使用for循环。如果它是一个左括号,我将它推入堆栈,如果它是一个关闭元素,我检查堆栈的最后一个元素是否与字典中的值匹配。如果不是,则返回False,如果是,则返回True。
Any other suggestions to help the code would also be greatly appreciated. I use code runner for this and I can only use a stack and specifically a function (not a class) for this lab question
任何其他建议,以帮助代码也将不胜感激。我使用代码运行器,我只能使用一个堆栈,特别是一个函数(不是一个类)来解决这个实验问题
1 个解决方案
#1
Usually, there's a peek()
operation that gets the top element without removing it. If peek()
isn't supported, it can be simulated by pop
ping the top element and push
ing it back on. You don't need to do any of that here, though, because you can just pop
the element to compare it:
通常,有一个peek()操作获取顶部元素而不删除它。如果不支持peek(),可以通过弹出顶部元素并将其推回来进行模拟。但是,您不需要在此处执行任何操作,因为您可以弹出元素来比较它:
for element in text_list:
if element in opening_bracket_list:
s.push(element)
elif element in closing_bracket_dict:
if s.pop() != closing_bracket_dict[element]:
return False
You'll also need to return True
at the end if everything matched.
如果一切都匹配,你还需要在结尾返回True。
#1
Usually, there's a peek()
operation that gets the top element without removing it. If peek()
isn't supported, it can be simulated by pop
ping the top element and push
ing it back on. You don't need to do any of that here, though, because you can just pop
the element to compare it:
通常,有一个peek()操作获取顶部元素而不删除它。如果不支持peek(),可以通过弹出顶部元素并将其推回来进行模拟。但是,您不需要在此处执行任何操作,因为您可以弹出元素来比较它:
for element in text_list:
if element in opening_bracket_list:
s.push(element)
elif element in closing_bracket_dict:
if s.pop() != closing_bracket_dict[element]:
return False
You'll also need to return True
at the end if everything matched.
如果一切都匹配,你还需要在结尾返回True。