Maximum depth of nested brancket

Question.
Write a function nestingdepth(s) that takes as input a string s and computes the maximum nesting depth of brackets if has properly nested brackets. If the string is not properly matched, your function should return -1.
Hint: Use the function matched() from the practice assignment.
Here are some examples to show how your function should work.

>>> nestingdepth("zb%78")
 0 
 >>> nestingdepth("(7)(a")
 -1 
 >>> nestingdepth("a)*(?") 
-1
 >>> nestingdepth("((jkl)78(A)&l(8(dd(FJI:),):)?)") 
4

Solution:-

If the string has valid brackets, I'm checking for the maximun number of "(".



def matched(s):
  a = 0
  for i in range(0, len(s)):
    if s[i] == '(':
      if a >= 0:
        a = a + 1
    elif s[i] == ')':
      a = a - 1
  if a == 0:
    return True
  else :
    return False
def nestingdepth(n):
    if matched(n) == False:
        return -1
    count = 0
    for i in n:
        if i == "(":
            count+=1
    if count == 0:
        return 0
    else:
        ct = 0
        maxi = 0
        for j in n:
            if j == "(":
                ct +=1
                if ct > maxi:
                    maxi = ct
            elif j == ")":
                ct -=1
        return maxi

Comments

Popular posts from this blog

Prime partitioning a number

Rotating a list

Alternating prime and square