How Do You Write a Palindrome Testing Program in Python That Ignores Punctuation and Spaces?

Problem scenario
You want to write a palindromic testing program without importing any modules that ignores a string's punctuation or spaces. What do you do?

Solution
Use this program:

def is_palindrome(s: str) -> bool:
    # i moves forward, and j moves backward
    i, j = 0, len(s) -1
    while i < j:
        while not s[i].isalnum() and i < j:
            i += 1
        while not s[j].isalnum() and i < j:
            j -= 1
        if s[i].lower() != s[j].lower():
            return False
        i, j = i + 1, j - 1
    return True

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

print(is_palindrome("aaaabaabaa"))

To buy the cited book, click here.

Leave a comment

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