Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading