Palindrome String check using recursion in Python

Palindrome String check using recursion in Python

Recursion of function is one of the interesting feature of any function of recursive nature. Benefit of using recursion is 1. Less line of code for implementation. 2. No need to write iterative statement multiple time. and easy to learn. In case of recursion the function use to call itself again and again till it reaches at bottom and returns to its caller(self) with calculated value. The self will again calculate next level of value and return to its caller. It goes to continue till it comes out from the very fist call of function. Here We have implemented Palindrome String check using Recursion function.

'''
Created on Jan 8, 2020
@author: admin@pythonport.com
'''
word = input("Enter word to check palindrom string - ")
def palindromCheck(word):
    length = len(word)
    if length == 0 or length == 1:
        return "Palindrom String"
    elif word[0] == word[length - 1] :        
        return palindromCheck(word[1:length - 1])        
    else :
        return "Not Palindrom String"

status = palindromCheck(word)    
print("{0} is {1}".format(word, status))

Here function palindromCheck() is a recursive function which is called from main once by passing the word to check palindrome. Now this function is called again and again by passing current words first position and last-1 position data. If every thing goes well it will return palindrome string else it will return not a palindrome string. Check your self for the output. Hope it helps.

Please comment if you want your valuable feedback or code improvement advice to be added by me.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>