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
如果问题已经解决,请设置最佳答案 |