为什么这个函数在传递索引对字符串进行切片时会发生溢出?
Why does overflow occur in this function when passing an index to slice a string?
我有以下函数来计算字符串中唯一回文的数量。我试图通过跟踪索引来提高算法效率,以避免在递归中每次都调用切片字符串。但是,当向递归函数 cp2 添加索引参数时,我得到了对堆栈的最大调用。有人可以解释为什么会这样吗?
def countPalindrones(word, d):
count = 0
if word in d:
return d[word]
if len(word) == 0:
return 1
for i in range(len(word)):
if isPalindrone(word[:i+1]):
count += countPalindrones(word[i+1:], d)
d[word] = count
return count
# overflow ???
def cp2(word, index, d):
count = 0
if word[index:] in d:
return d[word[index:]]
if len(word[index:]) == 0:
return 1
for i in range(len(word[index:])):
if isPalindrone(word[index:][:i+1]):
count += cp2(word, i + 1, d)
d[word[index:]] = count
return count
进行递归调用时,您是从索引 1
开始,而不是从 index
开始递增。递归应该是:
count += cp2(word, index + i + 1, d)
此外,您可以从 1
开始您的范围,而不是 0
.
,而不是在循环中写入 i + 1
for i in range(1, len(word[index:])):
if isPalindrone(word[index:][:i]):
count += cp2(word, i, d)
d[word[index:]] = count
我有以下函数来计算字符串中唯一回文的数量。我试图通过跟踪索引来提高算法效率,以避免在递归中每次都调用切片字符串。但是,当向递归函数 cp2 添加索引参数时,我得到了对堆栈的最大调用。有人可以解释为什么会这样吗?
def countPalindrones(word, d):
count = 0
if word in d:
return d[word]
if len(word) == 0:
return 1
for i in range(len(word)):
if isPalindrone(word[:i+1]):
count += countPalindrones(word[i+1:], d)
d[word] = count
return count
# overflow ???
def cp2(word, index, d):
count = 0
if word[index:] in d:
return d[word[index:]]
if len(word[index:]) == 0:
return 1
for i in range(len(word[index:])):
if isPalindrone(word[index:][:i+1]):
count += cp2(word, i + 1, d)
d[word[index:]] = count
return count
进行递归调用时,您是从索引 1
开始,而不是从 index
开始递增。递归应该是:
count += cp2(word, index + i + 1, d)
此外,您可以从 1
开始您的范围,而不是 0
.
i + 1
for i in range(1, len(word[index:])):
if isPalindrone(word[index:][:i]):
count += cp2(word, i, d)
d[word[index:]] = count