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
- Create a file iterator.
- 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 thestr.strip()
to each line read. The result is that we have an iterator that provides strings without the newline character. - Define an anonymous function using
lambda
keyword that returns true if the input string is a palindrome. - Python idiom for returning a reversed sequence (a string is a sequence of characters).
- Use the
filter
function to return a list of palindromes.
Using this input file …
add dad dam mad made madam set
… the result of running the functional script is:
['dad', 'madam']
No comments:
Post a Comment