Home > Mobile >  Why does overflow occur in this function when passing an index to slice a string?
Why does overflow occur in this function when passing an index to slice a string?

Time:02-19

I have the following function which counts the number of unique palindromes in a string. I am trying to make the algorithm efficient by keeping track of an index to avoid having to call the sliced string each time in the recursion. However when adding an index parameter to the recursive function cp2 I am getting max calls to the stack. Can someone explain why this is occuring?

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 

CodePudding user response:

When you make the recursive calls, you're starting from index 1, rather than incrementing from index. The recursion should be:

count  = cp2(word, index   i   1, d)

Also, instead of writing i 1 in the loop, you can start your range from 1, instead of 0.

    for i in range(1, len(word[index:])):
        if isPalindrone(word[index:][:i]):
            count  = cp2(word, i, d)
            d[word[index:]] = count
  • Related