|
发表于 2023-10-26 16:19:15
|
显示全部楼层
Here's the corrected code for the q5_parentheses function that uses a stack to check if parentheses are balanced:
- def q5_parentheses(rstring):
- stack = []
- opening = set(["(", "[", "{"])
- closing = set([")", "]", "}"])
- for char in rstring:
- if char in opening:
- stack.append(char)
- elif char in closing:
- if not stack:
- return False
- top = stack.pop()
- if (top == "(" and char != ")") or (top == "[" and char != "]") or (top == "{" and char != "}"):
- return False
- return len(stack) == 0
复制代码
Now, let's test the function with the provided test cases:
- assert not q5_parentheses("{")
- assert q5_parentheses("{[()]}")
- assert not q5_parentheses("{[(])}")
复制代码
The function should pass these assertions without raising any exceptions.
请注意,本回答来自GPT-4
如果问题已经解决,请设置最佳答案 |
|