Tuesday, 20 September 2016

Bracket Match

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.


def matched(s):
    op=0
    for i in range(len(s)):
        if s[i]==")":
            if op==0:
                return False
            else:
                op=op-1
        elif s[i]=="(":
            op=op+1
    if(op==0):
        return True
    else:
        return False
 

No comments:

Post a Comment