将迭代转换为递归

时间:2013-08-02 00:22:06

标签: python recursion python-3.x iteration

我想检查输入的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,就停止。

2 个答案:

答案 0 :(得分: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意味着你得到了适当的平衡。任何其他意味着你不平衡

答案 1 :(得分: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条件,上述算法考虑了在相应的左括号之前出现的情况 - 因此解决了原始问题中存在的问题代码。