Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple Palindrome
#1
Hi. I have simple program which checks if a string is a palindrome
def is_palindrome(i):
   if len(i) <= 1:
       return True
   else:
       if i[0] != i[len(i)-1]:
           return False
       else:
           return is_palindrome(i[1:len(i)-1])
print(is_palindrome("kajak"))
Unfortunately, when I write a word with a capital letter the result is "false". Please help. What to do and what to add to my code so that the same text in upper or lower case will be considered "True"?
Reply
#2
One easy method is to convert your string to all lower case, then run the palindrome check on the converted string.
>>> s = "MixedCase"
>>> s = s.lower()
>>> print(s)
mixedcase
Reply
#3
Thanks! All the code looks like this:
s = "Kajak kajak"
s = s.lower()

def is_palindrome(i):
   if len(i) <= 1:
       return True
   else:
       if i[0] != i[len(i)-1]:
           return False
       else:
           return is_palindrome(i[1:len(i)-1])
print(is_palindrome(s))
Reply
#4
reverse string works good to reduce iterations,

def is_palindrome(i):
    if len(i) <= 1 or i.lower() == i[::-1].lower():
        return True
    else:
        return False
 
print(is_palindrome("kaJAK"))
Best Regards,
Sandeep.

GANGA SANDEEP KUMAR
Reply
#5
It always good to have common understanding of terms (supposedly Socrates has said "The beginning of wisdom is the definition of terms.").

Palindrome according to Wikipedia:

Quote:A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam, racecar.
/.../
Sentence-length palindromes ignore capitalization, punctuation, and word boundaries.

So maybe it's a good idea to check whether code recognizes palindromes like "Madam, I'm Adam" and "Never odd or even"
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Palindrome in Python - result always false RavCOder 13 6,602 Oct-16-2019, 01:38 PM
Last Post: perfringo
  Palindrome mp3909 3 4,191 Oct-18-2017, 01:54 PM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020