1

我想检查用户输入的和的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,stop.s

4

2 回答 2

4
>>> 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意味着你已经适当地平衡了。其他任何事情都意味着你不平衡

于 2013-08-02T00:31:02.110 回答
3

算法的直接等效转换如下所示:

def check(string, counter=0):
  if not string:
    return "Balanced" if counter == 0 else "Unbalanced"
  elif counter < 0:
    return "Unbalanced"
  elif string[0] == "(":
    return check(string[1:], counter+1)
  elif string[0] == ")":
    return check(string[1:], counter-1)
  else:
    return check(string[1:], counter)

像这样使用它:

check("(())")
=> "Balanced"

check(")(")
=> "Unbalanced"

请注意,由于条件,上述算法考虑了右括号出现相应的左括号之前的elif counter < 0情况 - 因此修复了原始代码中存在的问题。

于 2013-08-02T00:30:55.360 回答