8 Feb 2015

Semordnilap using Recursion

#PYTHON

'''
A semordnilap is a word or a phrase that spells a different word when backwards ("semordnilap" is a semordnilap of "palindromes"). Here are some examples:

    nametag / gateman
    dog / god
    live / evil
    desserts / stressed
 

Recursive program, semordnilap, that takes in two words and says if they are semordnilap.
'''

'''
 
This wrapper function performs some checks, then makes a call to the recursive function
'''

def semordnilapWrapper(str1, str2):
    # A single-length string cannot be semordnilap
    if len(str1) == 1 or len(str2) == 1:
        return False

    # Equal strings cannot be semordnilap
    if str1 == str2:
        return False

    return semordnilap(str1, str2)




def semordnilap(str1, str2):
    '''

    returns: True if str1 and str2 are semordnilap;
             False otherwise.
    '''

    if len(str1)<>len(str2) or str1[0]<>str2[len(str2)-1] :
        return False
    elif len(str1)==1:
        return True
    else:
        return semordnilap(str1[1:],str2[:-1])


Categories: , , ,

0 comments:

Post a Comment

Copyright © UPgradeCODING | Powered by Blogger