Turning iteration into recursion

后端 未结 2 413
-上瘾入骨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.

    0 讨论(0)
  • 2021-01-25 04:25
    >>> 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

    0 讨论(0)
提交回复
热议问题