Advertisement
uopspop

Untitled

Oct 17th, 2018
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.01 KB | None | 0 0
  1. """
  2. Exercise 6.3. A palindrome is a word that is spelled the same backward and forward, like “noon”
  3. and “redivider”. Recursively, a word is a palindrome if the first and last letters are the same and the
  4. middle is a palindrome.
  5.  
  6. my second attempt:
  7.    new concept: 'abc'[-100,300] is a valid syntax. And we get an empty string
  8. """
  9.  
  10. def is_palindrome(word):
  11.     """ empty string is a palindrome so is a character """
  12.     if len(word) <= 1:
  13.         return True
  14.    
  15.     if word[0] == word[-1]:
  16.         return is_palindrome(middle(word))
  17.     else:            
  18.         return False        
  19.  
  20. def middle(word):
  21.     """Returns all but the first and last characters of a string."""
  22.     return word[1:-1]
  23.  
  24. print(': ' + str(is_palindrome(''))) #True
  25. print('j: ' + str(is_palindrome('j'))) #True
  26. print('kk: ' + str(is_palindrome('kk'))) #True
  27. print('noon: ' + str(is_palindrome('noon'))) #True
  28. print('abc: ' + str(is_palindrome('abc'))) #False
  29. print('redivider: ' + str(is_palindrome('redivider'))) #True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement