Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: recursive check to determine whether string is a palindrome

My task is to define a procedure is_palindrome, that takes as input a string, and returns a boolean indicating if the input string is a palindrome. In this case a single letter should return True, as should an empty string ''.

Unfortunately, I'm not getting the expected results. I appreciate the help.

My code version 1:

def is_palindrome(s):
    if s == '':
        return True
    else:
        if (ord(s[0]) - ord(s[len(s)-1])) == 0:
            is_palindrome(s[1:len(s)-1])
        else:
            return False

print is_palindrome('')
#>>> True    (expected = True)

print is_palindrome('abab')
#>>> False    (expected = False)

print is_palindrome('abba')
#>>> None    (expected = True)

print is_palindrome('andrea')
#>>> None    (expected = False)

print is_palindrome('abaaba')
#>>> None    (expected = True)

I followed my code through the debugger and it seems the logic is correct as the code takes the appropriate path. However, the end result seems to switch to 'None' for some of the cases as highlighted above.

If I change my code to the following:

My code version 2:

def is_palindrome(s):
        if s == '':
            result = True
        else:
            if (ord(s[0]) - ord(s[len(s)-1])) == 0:
                is_palindrome(s[1:len(s)-1])
            else:
                result = False
        return result

print is_palindrome('')
#>>> True    (expected = True)

print is_palindrome('abab')
#>>> False    (expected = False)

print is_palindrome('abba')
#>>> Error    (expected = True)
UnboundLocalError: local variable 'result' referenced before assignment 

print is_palindrome('andrea')
#>>> Error   (expected = False)         
UnboundLocalError: local variable 'result' referenced before assignment

print is_palindrome('abaaba')
#>>> Error    (expected = True)
UnboundLocalError: local variable 'result' referenced before assignment
like image 271
codingknob Avatar asked Dec 01 '22 22:12

codingknob


1 Answers

In your first example, you forgot a return statement:

def is_palindrome(s):
    if s == '':
        return True
    else:
        if (ord(s[0]) - ord(s[len(s)-1])) == 0:
            # v-- forgot this here
            return is_palindrome(s[1:len(s)-1])
        else:
            return False
like image 180
mVChr Avatar answered Dec 24 '22 00:12

mVChr