我想检查用户输入的string是否有平衡数量的(和)
例如。 ()( 不平衡 (()) 是平衡的
def check(string):
counter=0
string=string.replace(" ","")
if string[0] is "(":
for x in string:
if x is "(":
counter=counter+1
elif x is ")":
counter=counter-1
if counter1 is 0:
print("Balanced")
else:
print("Unbalanced")
else:
print ("Unbalanced")
所以这是有效的,但是我如何用递归解决这个问题呢?我试图思考如何在每次递归调用它时减少变量,一旦它为 0,就停止。 s
请您参考如下方法:
>>> def check(mystr, barometer=0):
... if not mystr:
... return barometer
... elif mystr[0] == "(":
... return check(mystr[1:], barometer+1)
... elif mystr[0] == ")":
... return check(mystr[1:], barometer-1)
... else:
... return check(mystr[1:], barometer)
...
>>> for s in ["()", "(()", "(())", "()()"]: print(s, check(s))
...
() 0
(() 1
(()) 0
()() 0
0 表示您已达到适当的平衡。任何其他情况都意味着你不平衡
