我不是程序员。我一直在学习如何用Python编程。我编写了程序,检查所有左括号和所有右括号是否匹配。我在这个程序中使用了递归。但是这段代码包含太多行。我想简化这个程序,但递归应该保留!我已经编写了这个程序的另一个版本,我在其中使用了while循环。如果可能,请使用递归建议如何简化程序。
[] True ] False [ False ][ False [[]] True [[][]] True ][][ False etc.
# s should be a string; please pass zero as the second argument
def check_br(s, opening_br):
length=len(s)
if length==0:
print ("error")
return None
if length==1 and s[0]=="[":
opening_br+=1
return opening_br==0
if length==1 and s[0]=="]":
opening_br-=1
return opening_br==0
if s[0]=="[" and s[0] != s[1]:
if length==2:
return opening_br==0
else:
new_s=s[2:] # form a new string by removing two leading chars.
return check_br(new_s, opening_br)
elif s[0]=="]":
if opening_br>0:
opening_br-=1
new_s=s[1:] #form a new string by removing one leading char.
return check_br(new_s, opening_br)
else:
return False
elif s[0]=="[" and s[0] == s[1]:
new_s=s[1:] #form a new string by removing one leading char.
opening_br+=1
return check_br(new_s, opening_br)
为了检查程序的正确性,我在脚本中使用了以下内容作为示例:
m=']][['
print(check_br(m,0))
答案 0 :(得分:0)
这是一个很长的计划。除了计算当前打开的括号外,您不必做更多的事情。这个数字最后应为0,永远不会变为负数。
在我看来,递归通常不会使事情变得简单。
def check_br(s,count=0):
for c in s:
if c == "[":
count += 1
elif c == "]":
count -= 1
if count < 0:
return False
return not count
这是递归版本:
def check_br(s,count=0):
if not s:
return not count
else:
if s[0] == "[":
count += 1
elif s[0] == "]":
count -= 1
if count < 0:
return False
return check_br(s[1:],count)
让我们做一个测试:
for teststring in ("[] True",
"] False",
"[ False",
"][ False",
"[[]] True",
"[[][]] True",
"][][ False"):
print(teststring," --> ",check_br(teststring))
结果:
[] True --> True
] False --> False
[ False --> False
][ False --> False
[[]] True --> True
[[][]] True --> True
][][ False --> False