Search code examples
pythontail-recursionpalindromeinvariants

Is Palindrome? using invariant programming


The following code doesn't work.

def isPal(s):
    def checkPal(s, acc):
        if len(s) <= 1:
            return acc
        else:
            return checkPal(s[1:-1] (acc and (s[0] == s[-1])))
    return checkPal(s, True)

TypeError: 'str' object is not callable

Could you tell me please, what's wrong with it? I cannot find the bug.


Solution

  • The bug is here:

    return checkPal(s[1:-1] (acc and (s[0] == s[-1])))
    

    s[1:-1] is a string and it is followed by (...) which is interpreted as a function call.

    Probably, you want add a comma and change it to:

    return checkPal(s[1:-1], (acc and (s[0] == s[-1])))
    

    You can also skip brackets:

    return checkPal(s[1:-1], acc and (s[0] == s[-1]))