Turning iteration into recursion

2019-02-28 07:57发布

问题:

I want to check if the string user entered has a balanced amount of ( and )'s

ex. ()( is not balanced (()) is balanced

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")

so this works, but how do I solve this problem with recursion? I am trying to think how I can make a variable decrease each time i call it recursively and once it's 0, stop.s

回答1:

A direct, equivalent conversion of the algorithm would look like this:

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)

Use it like this:

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

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

Notice that the above algorithm takes into account cases where the closing parenthesis appears before the corresponding opening parenthesis, thanks to the elif counter < 0 condition - hence fixing a problem that was present in the original code.



回答2:

>>> 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 means you're properly balanced. Anything else means you're not balanced