jia jia - 4 months ago 14
Python Question

Recursively checking for balanced string in Python

I've been stuck on this for quite a while, I can't come up with recursive cases, in particular I don't understand how to split a list to check if its balanced.
If someone could help me I would really appreciate it.

def balanced_str(s):
"""
Return whether string s is balanced or not. A balanced string is one where
the string contains no parentheses
>>> balanced_str('a')
True
>>> balanced_str('abbcsi')
True
>>> balanced_str('ak)')
False
>>> balanced_str('hah(dh')
False
>>> balanced_str('()')
True
>>> balanced_str('(hghghgh)')
True
>>> balanced_str('((a))')
True
>>> balanced_str('((hahsh))')
True
>>> balanced_str('(gfjf)h)')
False
>>> balanced_str('(hhg)(hfhg)')
True
"""
if '(' not in s and ')' not in s:
return True
elif '(' in s and ')' not in s or ')' in s and '(' not in s:
return False
else:
if s[0] == '(' and s[len(s) - 1] == ')':
return balanced_str(s[1:len(s) - 2])

Answer

For a recursive approach, you can create a small helper function that takes more parameters (ie. the number of parens we've seen so far). Below this approach, you can see how you can do it without a helper function through the use of global

def balanced_str(s):
    """
    Return whether string s is balanced or not. A balanced string is one where
    the string contains no parentheses
    >>> balanced_str('a')
    True
    >>> balanced_str('abbcsi')
    True
    >>> balanced_str('ak)')
    False
    >>> balanced_str('hah(dh')
    False
    >>> balanced_str('()')
    True
    >>> balanced_str('(hghghgh)')
    True
    >>> balanced_str('((a))')
    True
    >>> balanced_str('((hahsh))')
    True
    >>> balanced_str('(gfjf)h)')
    False
    >>> balanced_str('(hhg)(hfhg)')
    True
    """
    return helper(s,0)

def helper(s, numP):
    if len(s)==0: return numP==0
    if numP < 0: return False
    if s[0] == "(": return  helper(s[1:], numP+1)
    elif s[0] == ")": return  helper(s[1:], numP-1)
    return helper(s[1:], numP)

Without helper:

def balanced_str(s):
    """
    Return whether string s is balanced or not. A balanced string is one where
    the string contains no parentheses
    >>> balanced_str('a')
    True
    >>> balanced_str('abbcsi')
    True
    >>> balanced_str('ak)')
    False
    >>> balanced_str('hah(dh')
    False
    >>> balanced_str('()')
    True
    >>> balanced_str('(hghghgh)')
    True
    >>> balanced_str('((a))')
    True
    >>> balanced_str('((hahsh))')
    True
    >>> balanced_str('(gfjf)h)')
    False
    >>> balanced_str('(hhg)(hfhg)')
    True
    """
    try:
        numP
    except NameError:
        numP = 0
        global numP
    if len(s)==0: return numP==0
    if numP < 0: return False
    if s[0] == "(":
        numP += 1
        return balanced_str(s[1:])
    elif s[0] == ")":
        numP -= 1
        return balanced_str(s[1:])
    return balanced_str(s[1:])