Is this considered a recursive solution?

Viewed 54

I am learning Python and came across a beautiful recursive function to determine if a string is a palindrome but when I try to reproduce the solution by myself, I came up with this very inelegant solution. Do you call this a recursive function or an iterative function? I would appreciate any ideas about how to think "recursively"?

def pal(s,i):

    if len(s)//2 ==i:
        return True

    else:
        if s[i] != s[len(s)-1-i]:
            return False
        else:
            i=i+1      
            return((pal(s,i)))
        
print(pal ("abccba",0))
1 Answers

Any function which calls itself is recursive; that's what the word means in this context.

Your code could be simplified somewhat by observing that else: is not necessary after return - if the condition was met, the rest of the code cannot execute because the return will already have exited the function.

However, a proper recursive solution to this problem would probably articulate a solution which is close to a prose description of the problem. Let's say that "a string is a palindrome if and only if it is at most a single character long, or if the first letter is equal to the last letter and the remainder of the string is also a palindrome." In code, this would look like

def palindrome(mystring):
    if len(mystring) <= 1:
        return True
    if mystring[0] != mystring[-1]:
        return False
    return palindrome(mystring[1:-1])
Related