Answer to Question #85157 in Python for samba shivudu

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
1
Expert's answer
2019-02-14T06:19:59-0500

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()



Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS