Sunday, February 25, 2018

Python program : To calculate the depth of nesting

For an expression with parentheses, we can define the nesting depth as the maximum number of parentheses that are open when reading the expression from left to right. For instance, the nesting depth of "(33+77)(44-12)" is 1, while the nesting depth of "(a(b+c)-d)(e+f)" is 2.

Write a Python function depth(s) that takes a string containing an expression with parentheses and returns an integer, the nesting depth of s. You can assume that s is well-parenthesized: that is, that is, every "(" has a matching ")" after it and every ")" has a matching "(" before it.

Here are some examples to show how your function should work.


>>> depth("22")
0
>>> depth("(a+b)(a-b)")
1
>>> depth("(a(b+c)-d)(e+f)")
2
 
 
ef depth(S):
    current_max = 0
    max = 0
    n = len(S)
 
    # Traverse the input string
    for i in range(0,n):
        if S[i] == '(':
            current_max += 1
 
            if current_max > max:
                max = current_max
        elif S[i] == ')':
            if current_max > 0:
                current_max -= 1
            else:
                return -1
 
    # finally check for unbalanced string
    if current_max != 0:
        return -1
 
    return max
 
Thanks
Happy Programming ! 

No comments:

Post a Comment

How can I run a C++ program directly from Windows?

How-can-I-run-a-C-program-directly-from-Windows