在Python中递归检查平衡字符串
我已经在这上面呆了很长一段时间了,我不能想出递归的例子,特别是我不知道如何分割一个列表来检查它是否平衡。 如果有人能帮助我,我将非常感激在Python中递归检查平衡字符串,python,recursion,Python,Recursion,我已经在这上面呆了很长一段时间了,我不能想出递归的例子,特别是我不知道如何分割一个列表来检查它是否平衡。 如果有人能帮助我,我将非常感激 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')
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])
一个简单的迭代方法是创建一个小型lexer。当开始括号
(
)出现时,它将增加计数器o
,如果结束括号)
出现时,它将减少计数器。如果同时搜索字符串时计数器o
为负值,或循环结束时计数器o
不为零,则测试失败:
def balanced_str(s):
o = 0
for c in s:
if c == ')':
if o <= 0:
# this only happens if there are more closing
# parentheses then opening parentheses.
return False
o -= 1
elif c == '(':
o += 1
# all parentheses should be closed
return o == 0
对于递归方法,您可以创建一个接受更多参数的小辅助函数(即,到目前为止我们看到的参数数量)。在这种方法下面,您可以看到如何通过使用
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)
def-balanced_str(s):
"""
返回字符串s是否平衡。平衡字符串是
该字符串不包含括号
>>>平衡结构(“a”)
符合事实的
>>>平衡街(“abbcsi”)
符合事实的
>>>平衡的(ak)
错误的
>>>平衡的_str('hah(dh'))
错误的
>>>平衡_str(“()”)
符合事实的
>>>平衡_str(‘(hgh)’)
符合事实的
>>>平衡_str(“((a))”)
符合事实的
>>>平衡的_str(“((hahsh))”)
符合事实的
>>>平衡_str(‘(gfjf)h)’)
错误的
>>>平衡的("(hhg)(hfhg))
符合事实的
"""
返回帮助程序(s,0)
def助手(s、numP):
如果len=0:返回numP=0
如果numP<0:返回False
如果s[0]==”(“:返回帮助程序(s[1:],numP+1)
elif s[0]==”:返回帮助程序(s[1:],numP-1)
返回帮助程序(s[1:],numP)
没有助手:
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:])
def-balanced_str(s):
"""
返回字符串s是否平衡。平衡字符串是
该字符串不包含括号
>>>平衡结构(“a”)
符合事实的
>>>平衡街(“abbcsi”)
符合事实的
>>>平衡的(ak)
错误的
>>>平衡的_str('hah(dh'))
错误的
>>>平衡_str(“()”)
符合事实的
>>>平衡_str(‘(hgh)’)
符合事实的
>>>平衡_str(“((a))”)
符合事实的
>>>平衡的_str(“((hahsh))”)
符合事实的
>>>平衡_str(‘(gfjf)h)’)
错误的
>>>平衡的("(hhg)(hfhg))
符合事实的
"""
尝试:
努普
除名称错误外:
numP=0
全球numP
如果len=0:返回numP=0
如果numP<0:返回False
如果s[0]==“(”:
numP+=1
返回平衡的字符串[1:]
elif s[0]==”):
numP-=1
返回平衡的字符串[1:]
返回平衡的字符串[1:]
以下是我的备选解决方案:
def balanced(iterable, semaphore=0):
if semaphore < 0 or len(iterable) == 0:
return semaphore == 0
first, *rest = iterable
return balanced(rest, semaphore + { "(": 1, ")": -1 }.get(first, 0))
我相信其他建议的解决方案也是如此,不仅仅是我的。这里有一个递归方法。我认为这是相当简洁和直观的
def is_balanced(s, c=0):
if len(s) == 0:
if c == 0:
return True
else:
return False
elif s[0] == "(":
c = c + 1
return is_balanced(s[1 : len(s)], c)
elif s[0] == ")":
c = c - 1
return is_balanced(s[1 : len(s)], c)
else:
return is_balanced(s[1 : len(s)], c)
我想你的意思是没有不匹配的括号,不是吗?@joelgoldstick-yesalt尽管这样做有效,OP要求递归算法我真的很喜欢这个解决方案。但是,虽然
semaphore
是嵌套“深度”的准确名称,但我个人倾向于调用变量depth
,而不是semaphore
,因为它更具描述性。
>>> balanced('a')
True
>>> balanced(['a', 'b', 'b', 'c', 's', 'i'])
True
>>> balanced('ak)')
False
>>> balanced(['h', 'a', 'h', '(', 'd', 'h'])
False
>>> balanced('()')
True
>>> balanced(['(', 'h', 'g', 'h', 'g', 'h', 'g', 'h', ')'])
True
>>> balanced('((a))')
True
>>> balanced(['(', '(', 'h', 'a', 'h', 's', 'h', ')', ')'])
True
>>> balanced('(gfjf)h)')
False
>>> balanced(['(', 'h', 'h', 'g', ')', '(', 'h', 'f', 'h', 'g', ')'])
True
def is_balanced(s, c=0):
if len(s) == 0:
if c == 0:
return True
else:
return False
elif s[0] == "(":
c = c + 1
return is_balanced(s[1 : len(s)], c)
elif s[0] == ")":
c = c - 1
return is_balanced(s[1 : len(s)], c)
else:
return is_balanced(s[1 : len(s)], c)