Dyland
Dyland

Reputation: 93

Using Recursion to Determine if a Word is a Palindrome

I am trying to determine if a given word is a palindrome.

The goal of my code is that the function will take a word, and remove it of any punctuation or spaces. If the length of the word is 0 or 1, it is returned that the word is a palindrome. I then check if the first and last letter are the same. If they aren't, it is returned that it is not a palindrome. If they first and last letters the same, I then want to replace those two letters with spaces and call my function again. The reason I replace the letters with spaces is so that it will be edited by my initial edit statements.

def palindrome(word):
    editWord = word.strip(" ").strip("!").strip("?")

    stringOne = "A palindrome"
    stringTwo = "Not a palindrome"

    if len(editWord) == 0 or len(editWord) == 1:
        return stringOne

    elif editWord[0] != editWord[-1]:
        return stringTwo

    else:
        word = editWord.replace(editWord[0], " ").replace(editWord[-1], " ")
        palindrome(word)
        return stringOne

print(palindrome("area"))

When tested with single letters it functions properly, as well if I test words like 'are' which obviously is not a palindrome. However, if I call the word area it returns "A palindrome" when it is not. This makes it seem like it is not calling my function again. Any suggestions on why this is happening?

Upvotes: 0

Views: 79

Answers (2)

Mark
Mark

Reputation: 92461

Another alternative to replacing the letters while still doing this recursively to to keep track of the index in the word and increment it on recursion. This saves you from having to make new slices on each recursion. In this case your edge case will be when the index is in the middle of the word.

def palindrome(word, i = 0):
    if i >= len(word)//2:
        return True
    if word[i] != word[-(i+1)]:
        return False
    return palindrome(word, i+1)

palindrome("mrowlatemymetalworm") # true

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114548

For recursion to work properly here, your else statement should say something along the lines of "the word is a palindrome if the outer characters are equal and the remainder is also a palindrome". Instead, your code is replacing all occurrences of the outer characters with spaces, checking if the word is a palindrome, and ignoring the result to always return "yes".

You can do a proper recursion using slicing instead of replacement:

else:
    return palindrome(editWord[1:-1])

Upvotes: 2

Related Questions