2017-08-09 9 views
-6

括弧付きの式では、左から右に式を読み込むときに開いている括弧の最大数としてネスティングの深さを定義できます。例えば、入れ子の深さは「(a + b)+ d)(e + f)」は2であるのに対し、「(33 + 77)(44-12)」の入れ子の深さは1である。Pythonプログラミングの文字列処理

括弧で囲まれた式を含む文字列を引数に取り、sのネスト深度である整数を返すPython関数の深さを記述します。あなたはsが括弧で囲まれていると仮定することができます。つまり、すべての "("はそれ以降に) ")"が一致する "("の前にあります。 。あなたの関数がどのように動作するかを示すために、

depth("22") 
0 
depth("(a+b)(a-b)") 
1 
depth("(a(b+c)-d)(e+f)") 
2 

この

は私が試したものです

def depth(s): 
    count,i=0,0; 
    while i<=len(s): 
     if s[i]=='(': 
      count=count+1; 
     if s[i]==')': 
      return count 
     i=i+1; 
    return count 

    #this is what i tried. 
+4

は自分の宿題を投稿し、私たちはあなたのためにそれを行うには期待しないでください。 – csmckelvey

+0

何か試してみましたか? –

+1

ようこそ、私に問題がある場合は、[ask]と[mcve] – wwii

答えて

-1
def depth(s): 
count,i=0,0; 
while i<=len(s): 
    if s[i]=='(': 
     count=count+1; 
    if s[i]==')': 
     return count 
    i=i+1; 
return count 

#this is what i tried. 
+1

これは最初の終了後に最大深度が発生する場合には失敗します –

2

これを試してみてください:

def depth(s): 
    count = 0 
    max = 0 
    for character in s: 
     if character == "(": 
      count += 1 
      if count > max: 
       max = count 
     elif character == ")": 
      count -= 1 
    return max 
0

ちょうど楽しみのための再帰的な1あなたがそれをしたい場合は、:

def depth(str, index=0, counter=0, max_depth=0): 

    while index < len(str): 
     if str[index] == '(': 
      counter += 1 
      counter, index, max_depth = depth(str, index+1, counter, max_depth) 
      counter = 0 
      index += 1 
      continue 

     if str[index] == ')': 
      if counter > max_depth: 
       max_depth = counter 

      return counter, index, max_depth 

     else: 
      index += 1 

    return max_depth