Monday, February 13, 2017

Palindrome Testing Recursively Python

Tags

Entered string is Palindrome or not can be tested using Recursion as Shown by Following Code::

Code::

def isletter(c):     #function to check that character c is a letter or not
    return ('a'<=c<='z')or ('A'<=c<='Z')

def paltest(line):
    if len(line)<=1:return True
    elif not isletter(line[0]):return paltest(line[1:])      #ignoring first not letter
    elif not isletter(line[-1]):return paltest(line[:-1])    #ignoring last not letter
    elif line[0].lower()!=line[-1].lower():return False      
    else:return paltest(line[1:len(line)-1])                 #palindrome testing recursive call


string=input("Enter any String: ")
if(paltest(string)) : print("Yes,Palindrome")
else: print("Not,Palindrome")

Output::