Turning iteration into recursion

后端 未结 2 414
-上瘾入骨i
-上瘾入骨i 2021-01-25 03:46

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

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

2条回答
  •  时光取名叫无心
    2021-01-25 04:12

    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.

提交回复
热议问题