j.beach
j.beach

Reputation: 53

Removing White Space in a Palindrome String

I'm trying to modify the code to ignore white spaces in a Palindrome String. For example, the code should mark Do Geese See God as Palindrome. I've been trying to use .replace(" ", ""), but either an error pops up or the Palindrome is returned as False.

stk = Stack()

for i in range(len(sentence)):
    stk.push(sentence[i])

    for i in range(stk.size()):
        stk.replace(" ","")

        if sentence[i] != stk.pop():
           return False;

    return True;

I'm trying to not use stk.item[-1] or stk.item == stk.item[::-1] in Stack, by the way.

Upvotes: 2

Views: 988

Answers (3)

j.beach
j.beach

Reputation: 53

I've modified the code to make this work:

def isPalindrome(sentence):          
   sentence = sentence.replace (' '. '')
   stk = Stack()
   for i in range(len(sentence)):
      stk.push(sentence[i])
   for i in range(stk.size()):
      stk.replace(' ','')
      if sentence[i] != stk.pop():
          return False;
   return True;

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522007

I would recommend just stripping all whitespace with a RegEx:

input = "  A man a plan a canal Panama "
input = re.sub(r'\s+', '', input)

This would also handle the cases of leading and trailing whitespace, which you probably also want to ignore.

Upvotes: 1

dwagon
dwagon

Reputation: 511

It may be a cut and paste error but you don't actually have a space in what you are replacing.

stk.replace(' ', '')

Upvotes: 0

Related Questions