Why all the testcases are not passing? palindrome program

Viewed 67

Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Why is the below solution not accepting some of the test cases?

s = "".join(s)
s = s.lower()
if s==s[::-1]:
    return "true"
else:
    return "false"

Input: s = "A man, a plan, a canal: Panama"

Output: true

This test case is accepted:

Input: s = "race a car"

Output: false

this test case is returning true instead of false

3 Answers

Currently it is returning false for both cases.

According to this part in the question

considering only alphanumeric characters and ignoring cases.

you could remove all non alphanumeric chars from the string first using re.sub and a pattern [^a-zA-Z0-9]+ matching all chars except the listed alphanumeric ranges.

import re
strings = [
    "race a car",
    "A man, a plan, a canal: Panama"
]

for s in strings:
    s = re.sub(r"[^a-zA-Z0-9]+", "", "".join(s).lower())
    if s == s[::-1]:
        print("true: for {0}".format(s))
    else:
        print("false: for {0}".format(s))

Output

false: for raceacar
true: for amanaplanacanalpanama

Python demo

If you don't plan on using regex, you can use isalnum() string method:

s = ''.join(element for element in s if element.isalnum()).lower()
if s==s[::-1]:
    print("true")
else:
    print("false")

All are returning false because you don't remove spaces and special characters...

A man, a plan, a canal: Panama becomes: amanap :lanac a ,nalp a ,nam a

Related