Palindrome recursion with whitespace and a function not working

Solution 1:

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!

Solution 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])

Solution 3:

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)

Solution 4:

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')