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
A direct, equivalent conversion of the algorithm would look like this:
Use it like this:
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
means you're properly balanced. Anything else means you're not balanced