Search code examples
pythonpython-3.xalgorithmpalindromedeque

How do I handle Palindrome with spaces in python?


I'm trying to check if a string is palindrome in python using deque. But the code below just checks a string with no space, how can I adjust it to a code which handles strings with spaces as well? e.g: It only works if I write the input as "BORROWORROB" but not when it's "BORROW OR ROB"

from pythonds.basic import Deque
def isPalindrome(word):
    if word is None:
        return False
    if len(word) <= 1:
       return True

    DQ = Deque()
    for w in word:
        DQ.addRear(w)

    while (DQ.size() > 1):
        front = DQ.removeFront()
        rear = DQ.removeRear()
        if front != rear:
            return False
    return True


def readInput():
    inp = input("Enter string: ")
    return inp

word = readInput()
print ("Is \"{}\" a palindrome: {}".format(word, isPalindrome(word)))

Solution

  • You have to remove white spaces before starting the logic of the function:

    from pythonds.basic import Deque
    def isPalindrome(word):
        word = word.replace(" ", "")
        if word is None:
            return False
        if len(word) <= 1:
           return True
    
        DQ = Deque()
        for w in word:
            DQ.addRear(w)
    
        while (DQ.size() > 1):
            front = DQ.removeFront()
            rear = DQ.removeRear()
            if front != rear:
                return False
        return True
    
    
    def readInput():
        inp = input("Enter string: ")
        return inp
    
    word = readInput()
    print ("Is \"{}\" a palindrome: {}".format(word, isPalindrome(word)))