Question #85157

Write a function matched(s) that takes as input a string s and checks if the brackets "(" and ")" in s are matched: that is, every "(" has a matching ")" after it and every ")" has a matching "(" before it. Your function should ignore all other symbols that appear in s. Your function should return True if s has matched brackets and False if it does not.
Hint: Keep track of the nesting depth of brackets. Initially the depth is 0. The depth increases with each opening bracket and decreases with each closing bracket. What are the constraints on the value of the nesting depth for all brackets to be matched?
Here are some examples to show how your function should work.
>>> matched("zb%78")
True
>>> matched("(7)(a")
False
>>> matched("a)*(?")
False
>>> matched("((jkl)78(A)&l(8(dd(FJI:),):)?)")
True

Expert's answer

def matched(s):

depth = 0

for x in s:

if x == '(':

depth += 1

elif x == ')' and depth != 0:

depth -= 1

return depth == 0

def matched2(s):

depth = 0

for x in s:

if x == '(':

depth += 1

elif x == ')': # and depth != 0:

depth -= 1 # this is not correct

return depth == 0

def main():

print(matched("zb%78")) # True

print(matched("(7)(a")) # False

print(matched("a)*(?")) # False

print(matched("((jkl)78(A)&l(8(dd(FJI:),):)?)")) # True

print()

print(matched2("zb%78")) # True

print(matched2("(7)(a")) # False

print(matched2("a)*(?")) # True

print(matched2("((jkl)78(A)&l(8(dd(FJI:),):)?)")) # True

if __name__ == '__main__':

main()

## Comments

## Leave a comment