Whalefall126 发表于 2023-10-26 16:18:53

Write a Python program to check if parentheses are balanced using a stack. Use the method q5_parentheses, which returns True if balanced. Otherwise, False. A set of parentheses is balanced if for every opening parenthesis there is a closing and matching parenthesis. Hence:

    ({[]})()
is balanced, while:

    ({[}])
is not.

def q5_parentheses(rstring):
   



assert not q5_parentheses ("{")
assert q5_parentheses ("{[()]}")
assert not q5_parentheses ("{[(])}")

求解,chat和bard都不对

陶远航 发表于 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
如果问题已经解决,请设置最佳答案
页: [1]
查看完整版本: