python编程字符串处理
问题描述:
对于带括号的表达式,我们可以将嵌套深度定义为在从左向右读取表达式时打开的最大括号数。例如,“(33 + 77)(44-12)”的嵌套深度为1,而“(a(b + c)-d)(e + f)”的嵌套深度为2.python编程字符串处理
编写一个Python函数深度(s),它接受一个包含带圆括号的表达式的字符串并返回一个整数,即s的嵌套深度。你可以认为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.
答
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
this将在第一次关闭后发生最大深度的任何情况下失败 –
答
试试这个:
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
答
递归一个只是为了好玩,如果你想:
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
不要只发布你的功课,希望我们为你做它。 – csmckelvey
你有尝试过什么吗? –
欢迎来到SO,请阅读 - [问]和[mcve] – wwii