根据docstring,我正在尝试做一个稍微高级一些的回文。但是我不能让它起作用。我走的路对不对?到目前为止,这就是我所拥有的:
def pal_length(s: str, n: int) -> bool:
'''Return True iff s has a palindrome of length exactly n.
>>> pal_length('abclevel', 5)
True
>>> pal_length('level', 2)
False
'''
if not s:
return True
else:
index = 0
while index < len(s):
if s[index] == s[index+n]:
return pal_length(s[index+1:index+n-1],n-1)
index += 1
return False我试图不使用任何导入模块等,只是直接递归。
任何帮助都是非常感谢的。谢谢。
发布于 2014-04-13 21:58:47
我觉得你的索引有点离谱。不是应该吗
index = 0
while index < len(s) - n + 1:
if s[index] == s[index+n-1]:
return pal_length(s[index+1:index+n-1], n-2)
index += 1
return Falsehttps://stackoverflow.com/questions/23048831
复制相似问题