Search code examples
python-3.xrecursionpalindrome

Recursive palindrome check - having issues when recalling the function


The problem is simple, check if palindrome or not using recursion. They also provided a template so I can't change that. The template:

def isPalindrome(s): # Wrapper function
   def isPalindromeRec(s,low,high):
      """ Recursive function which checks if substring s[low ... high]     is palindrome
      returns a True/False value"""

   n = len(s)
   return isPalindromeRec(s,0,n-1)

I am nearly there but I think I am having trouble understanding how recursion exactly works. (especially how the values changes in the recursion)

My code:

def isPalindrome(s): # Wrapper function
    def isPalindromeRec(s,low,high):
        if len(s)<=1:
            return True
        else:
            if s[0]==s[len(s)-1]:
                return isPalindromeRec(s[low+1:high],low+1,high-1)
            else:
                return False

    n = len(s)
    return isPalindromeRec(s,0,n-1)
print(isPalindrome("anna"))
print(isPalindrome("civic"))
print(isPalindrome("a"))
print(isPalindrome("tx1aa1xt"))
print(isPalindrome(""))
print(isPalindrome("Civic"))
print(isPalindrome("ab"))

this is the output:

runfile('/Users/Rayan/Desktop/AUB Spring 2019/EECE 230 /HW/Homework 7/Problem2.py', wdir='/Users/Rayan/Desktop/AUB Spring 2019/EECE 230 /HW/Homework 7')
True
True
True
False
True
False
False

the first false should be True. Thank you for your help!


Solution

  • Rewrote it:

    def isPalindrome(s):
        def isPalindromeRec(s,low,high):
    
            if (low == high): 
                return True
    
            if (s[low] != s[high]) : 
                return False
    
            if (low < high + 1) : 
                return isPalindromeRec(s, low + 1, high - 1); 
    
            return True
    
        n = len(s) 
        if (n == 0) : 
            return True
    
        return isPalindromeRec(s, 0, n - 1); 
    
    print(isPalindrome("anna"))
    print(isPalindrome("civic"))
    print(isPalindrome("a"))
    print(isPalindrome("tx1aa1xt"))
    print(isPalindrome(""))
    print(isPalindrome("Civic"))
    print(isPalindrome("ab"))
    
    output:
    True
    True
    True
    True
    True
    False
    False