Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What possible improvements can be made to a palindrome program?

I am just learning programming in Python for fun. I was writing a palindrome program and I thought of how I can make further improvements to it.

First thing that came to my mind is to prevent the program from having to go through the entire word both ways since we are just checking for a palindrome. Then I realized that the loop can be broken as soon as the first and the last character doesn't match.

I then implemented them in a class so I can just call a word and get back true or false.

This is how the program stands as of now:

class my_str(str):
        def is_palindrome(self):
                a_string = self.lower()
                length = len(self)
                for i in range(length/2):
                        if a_string[i] != a_string[-(i+1)]:
                                return False
                return True

this = my_str(raw_input("Enter a string: "))
print this.is_palindrome()

Are there any other improvements that I can make to make it more efficient?

like image 760
jokerdino Avatar asked Dec 02 '22 22:12

jokerdino


2 Answers

I think the best way to improvise write a palindrome checking function in Python is as follows:

def is_palindrome(s):
   return s == s[::-1]

(Add the lower() call as required.)

like image 195
NPE Avatar answered Dec 18 '22 06:12

NPE


What about something way simpler? Why are you creating a class instead of a simple method?

>>> is_palindrome = lambda x: x.lower() == x.lower()[::-1]
>>> is_palindrome("ciao")
False
>>> is_palindrome("otto")
True
like image 20
luke14free Avatar answered Dec 18 '22 07:12

luke14free