7.5 Test palindromicity - improved Python solution

#1

This solution uses O(1) additional space compared to the book’s Pythonic solution which uses O(n) space. It’s the same idea except it uses iterators to create each element on the fly rather than precompute the entire string.

from itertools import ifilter, imap, izip

def is_palindrome_pythonic(s):
    return all(
        i == j for i, j in izip(
            imap(str.lower, ifilter(str.isalnum, s)),
            imap(str.lower, ifilter(str.isalnum, reversed(s)))
        )
    )
0 Likes

#2

Hi @robc,

Great! Thanks for this sharing and I think your use of reversed(), which returns iterator, is the key to this. Because the original pythonic approach requires [::-1] which instantiated list causing O(n) additional space.

0 Likes