Question #80493

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.

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

2018-09-07T05:10:48-0400

Question #80493

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.

Answer:

The function is as follows:


def matched(s):
    brackets_counter = 0
    i = 0
    while brackets_counter >= 0 and i < len(s):
        if s[i] == '(':
            brackets_counter += 1
        elif s[i] == ')':
            brackets_counter -= 1
        i += 1
    if brackets_counter == 0:
        return True
    else:
        return False


The screenshot below shows how the function work.


>>> from matched import matched
>>> matched("zb%78")
True
>>> matched(" (7)(a")
False
>>> matched("a)*(?")
False
>>> matched(" ((jkl)78(A)&l(8(dd(FJI:),):?))")
True

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

Sreetam Das
04.02.21, 09:51

thanks

LATEST TUTORIALS
APPROVED BY CLIENTS