9f. Review: Palindromes#
Review after Chapter 9: Lists, from the class on palindromes. Each question builds on the one before it: first a function that tests one word, then functions that find the palindromes in a list and in a book, and last a recursive version of the test. The questions use for loops, while loops, string indexes, lists, reversed and join, opening a file (7c), and recursion (Chapter 5).
Try each question first, then open its Answer.
Questions#
A palindrome is a word that is spelled the same backward and forward, for example 'racecar', 'noon' and 'bob'. In these questions, uppercase and lowercase letters are different letters, so 'Bob' is not a palindrome.
Run the setup cell below first. In Colab, it downloads the file pg345.txt (the text of the book Dracula, from Project Gutenberg), and it makes two small text files, sun.txt and noon.txt. Question 4 reads these files.
from os.path import basename, exists
def download(url):
filename = basename(url)
if not exists(filename):
from urllib.request import urlretrieve
local, _ = urlretrieve(url, filename)
print("Downloaded " + str(local))
return filename
download('https://github.com/AllenDowney/ThinkPython/raw/v3/pg345.txt');
def make_file(filename, text):
"""Make a small text file for Question 4."""
file = open(filename, 'w')
file.write(text)
file.close()
make_file('sun.txt', 'The neon sun was hot.\nEve did not see the radar.\nWould you like a cold drink?\n')
make_file('noon.txt', 'At noon the level of the river was low.\n')
Question 1 (easy): write a function#
Write a function called isPalindrome that takes a string and returns True if the string is a palindrome and False otherwise.
Use a loop and two indexes: left starts at the first character and right starts at the last character. Compare the two characters; if they are different, the string is not a palindrome. Then move left one step to the right and right one step to the left.
Hint: how many times must the loop run? For 'racecar' (7 characters) you compare 3 pairs: r/r, a/a and c/c. The middle e does not need a comparison. 7 // 2 is 3.
Start from this header (replace ... with the body):
def isPalindrome(text):
...
Examples
isPalindrome('racecar')
True
isPalindrome('racebar')
False
isPalindrome('')
True
isPalindrome('x')
True
Answer
Solution 1 (a for loop; the loop variable is left):
def isPalindrome(text):
"""Return True if text is a palindrome and False otherwise."""
right = len(text) - 1
for left in range(len(text) // 2):
if text[left] != text[right]:
return False
else:
right -= 1
return True
Then try: isPalindrome('racecar').
range(len(text) // 2) is shorthand for 0, 1, 2, ... up to len(text) // 2 minus 1. For 'racecar', len('racecar') // 2 is 3, so the loop runs 3 times, with left equal to 0, 1 and 2. The for statement moves left for you, so you do not write left = 0 or left += 1. You must move right yourself (right -= 1).
As soon as one pair is different, return False ends the function. The return True runs only after the loop compared every pair and found no difference. It is after the loop, not in it: a return True inside the loop would end the function after the first pair.
Solution 2 (a while loop; you move both indexes yourself):
def isPalindrome(text):
"""Return True if text is a palindrome and False otherwise."""
left = 0
right = len(text) - 1
while left < right:
if text[left] != text[right]:
return False
left += 1
right -= 1
return True
The loop stops when the two indexes meet in the middle. Both solutions return True for '' and for a string of one character (the last two examples): the loop does not run, so nothing is different.
Question 2 (easy): write a function#
Write another function, isPalindrome2, that does the same test without a loop: make the reversed string, and compare it with the original string.
Use the built-in function reversed and the string method join. Be careful: reversed('abc') does not return a string, and it does not return a list. It returns a reversed object, which join can make into a string: list(reversed('abc')) is ['c', 'b', 'a'], and ''.join(reversed('abc')) is 'cba'.
Start from this header (replace ... with the body):
def isPalindrome2(text):
...
Examples
isPalindrome2('racecar')
True
isPalindrome2('racebar')
False
Answer
def isPalindrome2(text):
"""Return True if text is a palindrome and False otherwise."""
text_reversed = reversed(text)
text_reversed_str = ''.join(text_reversed)
return text_reversed_str == text
Then try: isPalindrome2('racecar').
''.join(...) puts the characters together with nothing between them, so text_reversed_str is the reversed string. A common mistake is str(reversed(text)): it gives a string that starts with '<reversed object ', not the reversed text, so the function would always return False.
The last line returns the value of the comparison text_reversed_str == text, which is already True or False. This longer version also works:
def isPalindrome2(text):
"""Return True if text is a palindrome and False otherwise."""
text_reversed_str = ''.join(reversed(text))
if text_reversed_str == text:
return True
else:
return False
But it is too wordy: return text_reversed_str == text is shorter and gives the same results. Use that form when a function returns the result of a comparison.
Question 3 (medium): write a function#
Write a function called findPalindromes that takes a list of words and returns a new list with only the words that are palindromes, in their original order. If no word is a palindrome, it returns an empty list.
Use your isPalindrome function from Question 1 (or isPalindrome2 from Question 2).
Start from this header (replace ... with the body):
def findPalindromes(list_of_words):
...
Examples
findPalindromes(['racecar', 'mom', 'blue', 'racebar', 'bob'])
['racecar', 'mom', 'bob']
findPalindromes(['mommy', 'good', 'bad'])
[]
Answer
def isPalindrome(text):
"""Return True if text is a palindrome and False otherwise."""
right = len(text) - 1
for left in range(len(text) // 2):
if text[left] != text[right]:
return False
else:
right -= 1
return True
def findPalindromes(list_of_words):
"""Return a list of the words in list_of_words that are palindromes."""
answer = []
for word in list_of_words:
if isPalindrome(word):
answer.append(word)
return answer
Then try: findPalindromes(['racecar', 'mom', 'blue', 'racebar', 'bob']).
(The block repeats isPalindrome from Question 1, so that you can run it on its own.)
This is the usual pattern for making a new list from an old list: start with an empty list, loop over the old list, and append each item that passes the test. isPalindrome(word) is already True or False, so the if does not need == True.
The return answer is after the loop. If it were inside the loop, the function would return after the first word.
Question 4 (medium): write a function#
Write a function called findPalindromesInFile that takes the name of a text file and returns a list of all the words in the file that are palindromes, in the order in which they appear. A word is a piece of a line between spaces, as split() gives it; do not remove punctuation or change uppercase letters.
Use your isPalindrome function from Question 1.
The setup cell made two small files. sun.txt has these three lines:
The neon sun was hot. Eve did not see the radar. Would you like a cold drink?
'Eve' is not a palindrome here, because 'E' and 'e' are different letters, and 'radar.' is not one, because it ends with a period. noon.txt has this one line:
At noon the level of the river was low.
The third example counts the palindromes in the book Dracula (pg345.txt, which the setup cell downloads).
Start from this header (replace ... with the body):
def findPalindromesInFile(filename):
...
Examples
findPalindromesInFile('sun.txt')
['did', 'a']
findPalindromesInFile('noon.txt')
['noon', 'level']
len(findPalindromesInFile('pg345.txt'))
8466
Answer
def isPalindrome(text):
"""Return True if text is a palindrome and False otherwise."""
right = len(text) - 1
for left in range(len(text) // 2):
if text[left] != text[right]:
return False
else:
right -= 1
return True
def findPalindromesInFile(filename):
"""Return a list of the words in the file filename that are palindromes."""
answer = []
for line in open(filename, encoding='utf-8'):
for word in line.split():
if isPalindrome(word):
answer.append(word)
return answer
Then try: findPalindromesInFile('sun.txt').
(The block repeats isPalindrome from Question 1, so that you can run it on its own.)
It is the same pattern as Question 3, with a nested loop: the outer loop gets each line of the file, and the inner loop gets each word of that line. For the file sun.txt, the outer loop runs 3 times (once for each line), and the inner loop runs once for each word of the line.
You can also call findPalindromes from Question 3 for the inner loop:
def isPalindrome(text):
"""Return True if text is a palindrome and False otherwise."""
right = len(text) - 1
for left in range(len(text) // 2):
if text[left] != text[right]:
return False
else:
right -= 1
return True
def findPalindromes(list_of_words):
"""Return a list of the words in list_of_words that are palindromes."""
answer = []
for word in list_of_words:
if isPalindrome(word):
answer.append(word)
return answer
def findPalindromesInFile(filename):
"""Return a list of the words in the file filename that are palindromes."""
answer = []
for line in open(filename, encoding='utf-8'):
answer += findPalindromes(line.split())
return answer
By the way: for pg345.txt the result has 8466 words, and most of them are 'I' (4498 times) and 'a' (2891 times): a word of one character is always a palindrome. The palindromes of three letters or more, in lowercase letters only, are these: 'dad, deed, did, ere, eve, eye, level, noon, redder, refer, sees'. Words with an uppercase letter or with punctuation, such as 'noon.' at the end of a sentence, are not found. To find them too, you could change each word with lower() and remove its punctuation before the test.
Question 5 (hard): write a recursive function#
Write a recursive version of the test, isPalindrome3: a function that calls itself.
The idea: a string is a palindrome if its first and last characters are the same and the string between them is a palindrome. For example, 'racecar' is a palindrome because 'r' equals 'r' and 'aceca' is a palindrome; 'aceca' is a palindrome because 'a' equals 'a' and 'cec' is a palindrome; and so on. A string with 0 or 1 characters is always a palindrome: that is the base case, where the function stops calling itself.
Hint: text[0] is the first character, text[-1] is the last character, and text[1:-1] is the string without its first and last characters: 'racecar'[1:-1] is 'aceca'.
Start from this header (replace ... with the body):
def isPalindrome3(text):
...
Examples
isPalindrome3('racecar')
True
isPalindrome3('racebar')
False
isPalindrome3('')
True
Answer
def isPalindrome3(text):
"""Return True if text is a palindrome and False otherwise."""
if len(text) <= 1:
return True
if text[0] != text[-1]:
return False
return isPalindrome3(text[1:-1])
Then try: isPalindrome3('racecar').
The function has the two parts of every recursive function:
The base case:
len(text) <= 1. The function returns without calling itself. Without a base case, the calls would never stop (Python stops them with aRecursionError). The base case must cover the empty string too:'noon'gets shorter by two characters with each call,'noon'[1:-1]is'oo'and'oo'[1:-1]is'', so it never has exactly one character.The recursive case: the function calls itself with a shorter string,
text[1:-1]. Each call is closer to the base case.
Note the word return in the last line. Without it, the function would call itself, ignore the result, and return None.
For 'racebar' the calls are isPalindrome3('racebar'), then isPalindrome3('aceba') ('racebar'[1:-1] is 'aceba'); there 'a' and 'a' are the same, so it calls isPalindrome3('ceb') ('aceba'[1:-1] is 'ceb'), where 'c' and 'b' are different, so it returns False. Each call returns that False to the call before it.
Summary and questions by Prof. Y. Rosenthal, based on Think Python: 3rd Edition by Allen B. Downey. Text license: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International