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: , , ,

Related Posts:

  • 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    do… Read More
  • Tower of Hanoi #Python ''' Recursive program to implement Tower of Hanoi for n rings and 3 stacks ''' def printMove(fr, to):    print('move from ' + str(fr) + ' to ' + str(to))def Towers(n, fr, to, spare):   … Read More
  • Longest substring in Alphabetical order #Python ''' Find the longest substring in alphabetical order in the given string ''' s = 'azcbobobegghakl' i=1subs=s[0]subs2=s[0]while(i<len(s)):    j=i    while(j<len(s)):  … Read More
  • Count of Substring in String #Python ''' Count the number of times the substring 'bob' appears in string s ''' s='azcbobobegghakl'i=0ocr=0while(i<(len(s)-2)):    ocr+=s.count('bob',i,i+3)    i+=1   &nbs… Read More
  • Counting Vowels #Python ''' The program counts number of vowels in a string s ''' s = 'azcbobobegghakl' s=s.lower()count=0i=0while (i<len(s)):    if (s[i] in 'aeiou'):        count+=1… Read More

0 comments:

Post a Comment

Copyright © 2025 UPgradeCODING | Powered by Blogger