81 876
Assignments Done
99%
Successfully Done
In November 2019

# 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 &quot;(&quot; and &quot;)&quot; in s are matched: that is, every &quot;(&quot; has a matching &quot;)&quot; after it and every &quot;)&quot; has a matching &quot;(&quot; 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. &gt;&gt;&gt; matched(&quot;zb%78&quot;) True &gt;&gt;&gt; matched(&quot;(7)(a&quot;) False &gt;&gt;&gt; matched(&quot;a)*(?&quot;) False &gt;&gt;&gt; matched(&quot;((jkl)78(A)&amp;l(8(dd(FJI:),):)?)&quot;) True
1
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!