08 April 2008

Functional Python Palindromes

To find all palindromes from a list of words in a file, one word per line, you could write a procedural Python program like this:

for row in file('test.txt'):
  s = row.strip()
  if s == s[::-1]:
    print s

Here's a functional Python version, with notes below:

from itertools import imap
filter(lambda s: s == s[::-1], imap(str.strip, file('test.txt')))
  5       3              4       2               1
  1. Create a file iterator.
  2. When we read a line from a file into a string, the string has a trailing newline character (e.g. 'add\n'). We want to remove that trailing newline character, so we use the itertools.imap() function to create a new iterator that applies the str.strip() to each line read. The result is that we have an iterator that provides strings without the newline character.
  3. Define an anonymous function using lambda keyword that returns true if the input string is a palindrome.
  4. Python idiom for returning a reversed sequence (a string is a sequence of characters).
  5. Use the filter function to return a list of palindromes.

Using this input file …


… the result of running the functional script is:

['dad', 'madam']