I want to check if the string
user entered has a balanced amount of (
and )
\'s
ex. ()(
is not balanced
(())
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.
>>> 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