Search code examples
pythonpalindrome

Valid Palindrome solution in Python not working


I'm working on a solution for finding a valid palindrome, where an empty string would be considered a valid palindrome. This question ignores any cases which are not alphanumeric. Following are some examples:

Input: "A man, a plan, a canal: Panama"
Output: true

Input: "race a car"
Output: false

I wrote a solution where if I encounter a non-alphanumeric character, that character would be skipped:

def isPalindrome(self, s):
1        """
2        :type s: str
3        :rtype: bool
4        """
5        """
6        for i in s:
7            if (i.isupper())==True:
8                i.lower()
9        """
10        if len(s)==0:
11            return True
12        print(s)

13        i = 0
14        j = len(s) - 1

15        while(i<=j):  
16            if s[i].isalnum()==False:
17                i+=1
18            elif s[j].isalnum() == False:
19                j-=1
20            elif s[i].islower() != s[j].islower():
21                return False
22            i+=1
23            j-=1
24            
25        return True

However I keep on getting the following result:

Your input
"A man, a plan, a canal: Panama"
stdout
A man, a plan, a canal: Panama


Output
false

Expected
true

What am I doing wrong?


Solution

  • The first problem jumped out at me as I was about to close this tab:

            elif s[i].islower() != s[j].islower():
    

    This is not the comparison you need. islower returns whether or not the letter is lower case. This will fail on your first attempt, comparing 'A'.islower() (which is False) against 'a'.islower() (which is True). The comparison you need is

            elif s[i].lower() != s[j].lower():
    

    i.e. drop both letters to lower-case and compare them.

    There are more problems in your index handling, but this -- and a few print commands -- should get you moving.