1

I have a palindrome recursion function, which works for every word except for ones with spaces. How do I fix the code to not take spaces into account?

def ispalindrome(word):
    if len(word) < 2: 
        return True
    if word[0] != word[-1]: 
        return False
    return ispalindrome(word[1:-1])
print(ispalindrome("taco cat"))
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Lamar
  • 217
  • 2
  • 10

4 Answers4

2

Simply modify the string so that the whitespace can be gone. one method is using the split join functions of python and the other is the usage of regex.

here's a sample of a running code:

def ispalindrome(word):
    if len(word) < 2: 
        return True
    if word[0] != word[-1]: 
        return False
    return ispalindrome(word[1:-1])

print(ispalindrome(''.join("taco cat".split())))

Output: True

I hope that helps!

2

Add that line in the function. This will remove white spaces and other tabular information.

def ispalindrome(word):
    word = word.strip() # remote white spaces and tabular information
    if len(word) < 2: 
        return True
    if word[0] != word[-1]: 
        return False
    return ispalindrome(word[1:-1])
Felipe Borges
  • 405
  • 4
  • 8
1

You should remove spaces in string at the beginning of the function, because space is a character too and function check for it too.

def ispalindrome(word):
    word = word.replace(' ', '')
    if len(word) < 2: 
        return True
    if word[0] != word[-1]: 
        return False
    return ispalindrome(word[1:-1])
print(ispalindrome("taco cat"))

There are different ways to remove spaces from string, these are:

1)

string = string.replace(" ", "")

2)

string = "".join(string.split())

3)

import re
pattern = re.compile(r'\s+') 
string = re.sub(pattern, '', string) 

4)

import string 
string = string.translate(None, ' \n\t\r')
1
class Solution:
    def recursive(self,s:str):
        string=''.join(char.lower() for char in s if char.isalnum())
        def dfs(s:str):
            if len(s)<=1:
                return True
            if s[0]==s[-1]:
                #reduce the bigger problem to smaller problem
                return dfs(s[1:-1])
        return dfs(string)
Yilmaz
  • 35,338
  • 10
  • 157
  • 202