steve
steve

Reputation: 61

Improving Python Palindrome code

So I recently implemented a code that checks a word to see if it's a palindrome.

def isPalindrome():
    string = input('Enter a string: ')
    string1 = string[::-1]
    if string[0] == string[(len(string)-1)] and string[1:(len(string)-2)] == string1[1:(len(string)-2)]:
            print('It is a palindrome')
    else:
        print('It is not a palindrome')
isPalindrome()

I was wondering if anyone could give me tips on simplifying the code.

Edit - If I were to make the function an iterative function with the statements string == string1, how would I stop the endless while loop? Would I need a count to stop the while loop?

Upvotes: 2

Views: 22716

Answers (10)

user9234737
user9234737

Reputation:

Here is a simple solution in just 1 LINE.

plandrom = lambda string: True if string == string[::-1] else False

Upvotes: 1

benlegendj
benlegendj

Reputation: 1

you can as well try this

def palindrome(str1):
    return str1==str1[::-1]
print(palindrome(str1)

the answer above returns a boolean according to the string given if it is a palindrome prints true else false

Upvotes: 0

TerryA
TerryA

Reputation: 60004

No need for such complex conditional. You already have a reversed string (string[::-1]).

All you need to do is this:

def isPalindrome():
    string1 = input('Enter a string: ')
    string2 = string1[::-1]
    if string1 == string2:
        return 'It is a palindrome'
    return 'It is not a palindrome'

isPalindrome()

(by the way don't use string as a variable name. That's the name of a built-in module)

It's better to return the strings instead of printing them. That way your function will not return None (preventing some stuff that could happen later)

Upvotes: 6

suma
suma

Reputation: 1

we could use reverse String function to verify Palindrome:

def palindrome(s):
    str=s[::-1]
    if s==str:
        return True
    else:
        return False

palindrome('madam')

Upvotes: 0

doe-eyed-
doe-eyed-

Reputation: 1

Simple way to write palindrome

a=raw_input("Enter the string : ")    # Ask user input

b= list(a)                            # convert the input into a list

print list(a)

b.reverse()                           # reverse function to reverse the 
                                      # elements of a list

print b

if list(a) == b:                      # comparing the list of input with b

   print("It is a palindrome")

else:

   print("It is not a palindrome")

Upvotes: 0

saravanan
saravanan

Reputation: 11

Here is another solution I came up with:

###Piece of code to find the palindrome####
def palindrome():
    Palindromee = input("Enter the palindrome \t:")
    index = 0
    length = len(Palindromee)
    while index < length:
         if Palindromee[0] == Palindromee[-1] :
               index +=1
    print ("Palindrome worked as expected")       

palindrome()

Upvotes: 0

gogasca
gogasca

Reputation: 10058

Check Counter from collections

from collections import Counter

def is_palindrome(letters):
    return len([v for v in Counter(letters).values() if v % 2]) <= 1

Upvotes: 0

user2109202
user2109202

Reputation: 11

So, I just got into learning python and I have been trying to these exercises, #8. Though I see that a lot of these answers are creating a new reverse string(which adds a memory overhead) and comparing both strings, I thought I could utilize lesser memory by doing this:

def is_palindrome(s):
    l=len(s)
    list_s=list(s)
    for i in range(0,l):                                            
        if(list_s[i] !=list_s[l-i-1]):
            return False
    else:
        return True

You can use a print statement to verify. All I am doing is comparing the first index to the last and the second index to the second last and so on. Hope that helps.

Upvotes: 0

James Sapam
James Sapam

Reputation: 16940

Please check this algorithm,

def is_palindrome(n):
   m = len(n)/2
   for i in range(m):
      j = i + 1
      if n[i] != n[-j]:
         return False
   return True

print is_palindrome('malayayalam')

Upvotes: 0

Nafiul Islam
Nafiul Islam

Reputation: 82550

You can do it in a one liner:

return "Is a palindrome" if string == string[::-1] else "Not a palindrome"

Sample script:

>>> string = "stanleyyelnats"
>>> print "Is a Palindrome" if string == string[::-1] else "Not a palindrome"
>>> Is a Palindrome

You can also do this (although its slower):

print "Is a Palindrome" if string == ''.join(reversed(string)) else "Not a palindrome"

Also, use raw_input and not input. Because input will be evaluated. Let me show you an example:

Script

inp = input("Evaluate ")

print inp

Run

Evaluate "cheese" + "cake"
cheesecake

Upvotes: 4

Related Questions