Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading