2

I'm trying to make a program that tests if a word is a palindrome using a recursive function. I pretty much have it working but I'm just having trouble with getting it to move on to the next letter if the first and last are the same.

word = input("enterword")
word = word.lower()

def palindrom(word):
    if len(word) == 1 or len(word) == 0:
        return 0;
    if word[0] == word[-1]:
        print(word[0], word[-1])
        palindrom(word);
    else:
        return 1;

test = palindrom(word)
if test == 0:
    print("Yes")
elif test == 1:
    print("No")

So right now it tests if the first and last letter are the same and if so, should run the function again. I just need to have it then check word[1] and word[-2] but I'm having some trouble. I tried splitting word and just popping the letters but it kept looking at the list as a length of 1. So if there is a way to get it to get the length of the whole split list, that would work as well.

Vinod Sharma
  • 883
  • 6
  • 13
user3769402
  • 201
  • 1
  • 4
  • 11
  • Awww, come on. There are dozens of questions about the exact same topic: http://stackoverflow.com/questions/952110/recursive-function-palindrome-in-python?rq=1 http://stackoverflow.com/questions/4666339/python-and-palindromes?rq=1 http://stackoverflow.com/questions/8769890/performance-of-various-methods-to-test-for-a-palindrome-python?rq=1 – tamasgal Mar 16 '15 at 20:41

4 Answers4

4

You're just missing the return statement when you call your method recursively and the correct slice:

def palindrom(word):
    if len(word) == 1 or len(word) == 0:
        return 0
    if word[0] == word[-1]:
        print(word[0], word[-1])
        return palindrom(word[1:-1])
    else:
        return 1
Celeo
  • 5,583
  • 8
  • 39
  • 41
0

You are missing return statement, also you need to pass reduced word palindrom(word[1:-1]) on each recursion.

word = "viooiv"
word = word.lower()


def palindrom(word):
    if len(word) == 1 or len(word) == 0:
        return 0 
    if word[0] == word[-1]:
        print(word[0], word[-1])
        return palindrom(word[1:-1])
    else:
       return 1 

test = palindrom(word)
if test == 0:
    print("Yes")
elif test == 1:
    print("No"

Output:

 ('v', 'v')
 ('i', 'i')
 ('o', 'o')
 Yes
Vinod Sharma
  • 883
  • 6
  • 13
0

Try calling palindrome on the word with this function:

def palindrome(word, i = 0):
    if i == len(word):
        return word[0] == word[-1]

    if word[i] == word[-i - 1]:
        return palindrome(word, i + 1)

    else:
        return False
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
0

A bit more shorter code:

def checkpalindrome(value):
    valuelen = len(value)
    if valuelen < 2:
        print("palindrome")
    else:
        checkpalindrome(value[1:valuelen-1]) if value[0] == value[-1] else print('Not palindrome')
Naveen Goyal
  • 93
  • 1
  • 1
  • 6