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.

Run this page on Colab

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

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

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'])
[]

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

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

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