Search code examples
pythonrecursionpalindrome

How to write a recursive function for palindromic primes?


I have been trying to write a Python program which uses a recursive function to find the palindromic primes between two integers supplied as input. Example of palindromic prime: 313

I already know how to write a recursive function for palindromes, but I am struggling with this one a lot. I would appreciate any help. Thanks


Solution

  • recursive function for palindromes

    Presumably to do the palindrome check recursively you check the outer characters:

    def is_pali(s):
        if len(s) <= 1:
            return True
        else:
            return s[0] == s[-1] and is_pali(s[1:-1])
    

    Now you can iterate over the numbers and see which are palindromes:

    [i for i in range(n, m) if is_pali(str(i))]