How Do You Write a Python Program without the import Statement That Palindromically Tests a String in Four Lines of Code?

Problem scenario
You want to avoid importing any modules in Python. You want to have a way to test if a string is a palindrome is four lines of code. What do you do?

Solution

def is_palindrome_pythonic(s):
    return all(a == b for a, b, in zip(
        map(str.lower, filter(str.isalnum, s)),
        map(str.lower, filter(str.isalnum, reversed(s)))))

# The above four lines of code were taken from page 78 of Elements of Programming Interviews in Python.

print(is_palindrome_pythonic("aaaabaabaa"))

To buy the cited book, click here.

Leave a comment

Your email address will not be published. Required fields are marked *