我一直堅持這個很長一段時間,我不能拿出遞歸的情況下,特別是我不明白如何分割列表來檢查它是否平衡。 如果有人能幫助我,我會非常感激。遞歸檢查Python中的平衡字符串
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])
我想你的意思是沒有不匹配的圓括號,不是嗎? –
@ joelgoldstick是 – jia