0

So I have this code for detecting if a string is a palindrome (the same forward and backwards) and I'm not sure how to change it to a recursive program

    def isPalindrome(string):
        i = 0
        j = len(string) - 1
        k = 0
        while (i <= j):
            if string[j] != string[i]:
                k = 1
            else:
                i += 1
                j -= 1
        if k == 0:
          return True
        else:
          return False
    def main():
        print("This program tests if strings are palindromes.")
        word = input("Enter a string: ")
        while word != "quit" :
           if isPalindrome(word) == True:
               print(word,"is a palindrome.")
           else:
               print(word,"is not a palindrome.")
           word = input("Enter a string: ")

    main()

I'm really bad with recursions and I don't really understand them any help would be great. Thanks

1 Answers1

1

Without Recursion:

Ideally you might not need recursion for palindrome detection. It can be done simply as below.

def is_palindrome(word):
    if word=="".join(reversed(word)):
        return True
    return False

Another shorter method

def is_palindrome(word):
    return word[::-1]==word

Using Recursions: For some reasons if you still require recursion and comfortable with arrays and indices, Use it like this.

def is_palindrome(word, end=0, start=0):
    if end == 0:
        end = len(word)-1
    if start >= end:
        return True
    if word[start] != word[end]:
        return False
    start = start+1
    end = end-1
    return is_palindrome(start, end, word)

word = 'ramar'
print (is_palindrome(word))

This will be more Pythonic way with recursion

def is_palindrome(word):
    if not word:
        return True
    else:
        return word[0]==word[-1] and is_palindrome(word[1:-1])
nehem
  • 12,775
  • 6
  • 58
  • 84