1

I try to write a function for palindrome.below is my code

def ispalindrome(string):
    if len(string) <= 1:
        return True
    else:
        if string[0] == string[-1]:
            return True
        else:
            return False

Only one thing I don't understand is one of my results it says "ispalindrome('123321') should return False", and my result for this one is true. I don't know what to do now. Anyone can help me correct this?

Siong Thye Goh
  • 3,518
  • 10
  • 23
  • 31
  • A very basic google search and this answer would have been easy to find. Check this [link](https://www.geeksforgeeks.org/python-program-check-string-palindrome-not/) – tidakdiinginkan Apr 02 '20 at 04:00
  • Does this answer your question? [How to check for palindrome using Python logic](https://stackoverflow.com/questions/17331290/how-to-check-for-palindrome-using-python-logic) – dspencer Apr 02 '20 at 04:03

1 Answers1

1

You just check the first and the last element, you didn't check the characther in the middle

def ispalindrome(x):
    if len(x) <= 1:
        return True
    else:
        n = len(x)
        for i in range(n//2):
            if x[i] != x[n-1-i]:
                return False
        return True

Also, "123321" is indeed a palindrome.

Siong Thye Goh
  • 3,518
  • 10
  • 23
  • 31