Improving Python Palindrome code - python

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?

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)

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

Here is a simple solution in just 1 LINE.
plandrom = lambda string: True if string == string[::-1] else False

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')

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.

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

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()

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")

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')

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

Related

How can I make sure a word is palindrome using Python while using recursion?

I am trying to create a code in which python asks the user for input or a word and it has to check whether it's a palindrome or not using recursion. If the word is not a palindrome through the reverse() function it will take in the string and, through recursion, return that string in reverse. It seems that I am able to take input and when I put in a word that's not a palindrome it gives me back the output needed. However it doesn't give back the word in reverse and also when I put a word that is a palindrome and it doesn't give the input back leaving a blank space in the output.
def reverse(choice, index, new_word):
if index < 0:
return new_word
else:
new_word += choice[index]
return reverse (choice, index - 1, new_word)
def palindrome():
new_word = ""
choice = input("Please enter a word to check if it is palindrome:")
result = reverse(choice, len(choice) - 1, new_word)
if result == choice:
print("That word",choice,"IS a palindrome")
else:
print("Sorry,",new_word,"is NOT a palindrome")
palindrome()
This is happening because you have set new_word to an empty string, and then you're taking the result of reverse() and storing that in another variable called result.
This should fix your issue:
def palindrome():
new_word = ""
choice = input("Please enter a word to check if it is palindrome:")
result = reverse(choice, len(choice) - 1, new_word)
if result == choice:
print("That word",choice,"IS a palindrome")
else:
# change here to result
print("Sorry,",result,"is NOT a palindrome")
Alternatively, you can use choice[::-1] to reverse a string. it is cleaner and you don't have to use recursion. However, the above fix will help you with the recursion bit as well.
Try the following:
def check_palindrome(word): # Creating function with 1 parameter: word
if word == word[:: -1]: # word[:: -1] reverses a string
return True # Return a true value if word is the same when reversed
else:
return False # Otherwise, return a false value
print(check_palindrome("racecar")) # Palindrome
print(check_palindrome("hello world")) # Not a palindrome
the syntax word[:: -1] reverses the word.

How do I return "Yes" if all words in the sentence are lowercase?

I can currently have my code return "Yes" for each character, but I'm not sure how to make the code return just ONE Yes at the end of the code, if every word in the sentence was lowercase. Here's what I have
sentence = "hello thEre is this aLL lowercase"
sent = sentence.split(" ")
lower = False
for wd in sent:
for ch in wd:
if ch.islower():
print("Yes")
lower = True
if not ch.islower():
print("No")
lower = False
I know I cannot have print("Yes") in the loop because it will print everytime, but I don't know how to do it any other way. Thanks for any help.
Here is one way to approach the solution.
I’m intentionally not providing any explanation, because it will help your learning to research the concepts on your own. Look into:
List comprehension
The all() function
Boolean tests
Sample code:
s = ‘lower case statement’
result = all([i.islower() for i in s.split()])
print('Yes' if result else 'No')
>>> ‘Yes’
I recommend taking each part of the short code apart to discover how it’s working.
Simplified:
Personally, I don’t mind sharing this in an educational setting, because part of learning to write Python (and code in general) is learning to write it efficiently. That said, here’s a simplified solution:
print('Yes' if s.islower() else 'No')
>>> ‘Yes’
If you only care about it being all lowercase then the first time you find a capital letter you should break out of the loop. Then only print yes if lower is true outside the loop.
I'm assuming this is an exercise, so I won't give any code.
You need to have a variable "any non-lowercase word found" that is set to false before the loop and set to true if a word is found that is not lowercase. If the variable is still false after the loop you can print "yes", otherwise not.
Maybe if you have written the code to implement this you will find that it can be optimized.
You can use isLower(), just remember to remove spaces
def checkLower(string):
string = string.replace(" ","")
print(string)
for i in string:
if i.islower() == False:
return "no"
return "yes"
You can simply do this way using .islower() because The islower() methods return True if all characters in the string are lowercase, Otherwise, It returns False.
sentence = "hello thEre is this aLL lowercase"
if(sentence.isLower()):
print('Yes')
else:
print('No')
sentence = "hello there this is all lowercase"
sent = sentence.split(" ")
lower = True
for wd in sent:
for ch in wd:
if not ch.islower():
lower = False
if lower:
print("Yes")
if not lower:
print("No")
I don't have much idea about python and how it works but here is the logic i added to the code provided.
Right now you are printing "Yes" every time you find a lowercase word.
def isAllLower(sentence):
sent = sentence.split(" ")
lower = False
for wd in sent:
for ch in wd:
if ch.islower():
lower = True
if not ch.islower():
lower = False
if lower == True:
print("Yes")
elif lower == False:
print("No")
isAllLower("hello thEre is this aLL lowercase")
The simplest by far way is to compare the lowered by default sentence using the lower() function, with the initial function!
def SentenceisLower(sentence):
sentencelower = sentence.lower()
if (sentence == sentencelower):
print("Yes!")
Where there is no reply in any other outcome!

Keep encountering "string index out of range' error in Python

I'm doing an assignment for an intro course in which I need to determine whether a string is a palindrome. Having trouble with this segment of the code:
def is_palindrome(letters):
if (len(letters))==0:
return True
elif len(letters)==1:
return True
elif (letters[end])==(letters[0]):
return is_palindrome(letters[(letters[0+1]):(letters[len(letters)-1])])
else:
return False
Your code is nearly correct, but you have errors in the slicing of the strings:
def is_palindrome(letters):
if (len(letters))==0:
return True
elif len(letters)==1:
return True
elif (letters[0])==(letters[-1]): # index [-1] gives the last letter
return is_palindrome(letters[1:-1]) # slice [1:-1] is the word without the first and last letter.
else:
return False
The above works.
I suggest you review this post that explains in details how slicing works: Explain Python's slice notation
Try these following codes:
def palindrome(text):
if text == text[::-1]:
print(text, 'is palindrome')
else:
print(text, 'is not palindrome')
palindrome('reser')
palindrome('reset')
str[::-1] will reverse the string. for more info, try help(slice).

Where's the bug in this function to check for palindrome?

Given below is the code to check if a list is a palindrome or not. It is giving correct output for 983. Where am I going wrong?
def palindrome(num):
flag=0
r=num[::-1]
for i in range (0, len(num)-1):
if(r[i]==num[i]):
flag=1
else:
flag=0
return flag
You should return as soon as there is a mismatch. Also, you just need to iterate till half the length:
def function(...):
...
for i in range (0, (len(num) + 1) / 2):
if r[i] != num[i]:
return False
return True
BTW, you don't need that loop. You can simply do:
def palindrome(num):
return num == num[::-1]
This would be easier:
def palindrome(num):
if num[::-1] == num:
return True
else:
return False
Your for loop checks all pairs of characters, no matter if it found mismatch or not. So, in case of string '38113' it will return True, because the flag variable will be set to True after the check for equality of last digit in '38113' and its reversed version '31183' (both equal to 3, while the string isn't a palindrome).
So, you need to return False right after you've found mismatch; if you checked all the characters and didn't find it - then return True, like so:
def palindrome(num):
r = num[::-1]
for i in range (0, len(num)-1):
if(r[i] != num[i]):
return False
return True
Also, as someone pointed out it'll be better to use python's slices - check out the documentation.
Just for the record, and for the ones looking for a more algorithmic way to validate if a given string is palindrome, two ways to achieve the same (using while and for loops):
def is_palindrome(word):
letters = list(word)
is_palindrome = True
i = 0
while len(letters) > 0 and is_palindrome:
if letters[0] != letters[-1]:
is_palindrome = False
else:
letters.pop(0)
if len(letters) > 0:
letters.pop(-1)
return is_palindrome
And....the second one:
def is_palindrome(word):
letters = list(word)
is_palindrome = True
for letter in letters:
if letter == letters[-1]:
letters.pop(-1)
else:
is_palindrome = False
break
return is_palindrome
str1=str(input('enter string:'))
save=str1
revstr=str1[::-1]
if save==revstr:
print("string is pailandrom")
else:
print("not pailadrom")
# We are taking input from the user.
# Then in the function we are reversing the input i.e a using
# slice [::-1] and
# storing in b
# It is palindrome if both a and b are same.
a = raw_input("Enter to check palindrome:")
def palin():
#Extended Slices to reverse order.
b = a[::-1]
if a == b:
print "%s is palindrome" %a
else:
print "%s is not palindrome" %a
palin()
this would be much easier:
def palindrome(num):
a=num[::-1]
if num==a:
print (num,"is palindrome")
else:
print (num,"is not palindrome")
x=input("Enter to check palindrome:")
palindrome(x)
Here in my opinion is the most elegant:
def is_palindrome(s):
if s != '':
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
return True
it's also the same code in the is_palindrome() function:
pip install is-palindrome
>>> from is_palindrome import is_palindrome
>>> x = "sitonapanotis"
>>> y = is_palindrome(x)
>>> y
True
Take care to note the hyphen vs underscore when installing vs. importing
a="mom"
b='mom'[::-1] # reverse the string
if a==b: # if original string equals to reversed
print ("palindrome ")
else:
print ("not a palindrome ")
def palindrome(a):
a=raw_input('Enter :')
b=a[::-1]
return a==b

Python reverse() for palindromes

I'm just getting started in python, and I'm trying to test a user-entered string as a palindrome. My code is:
x=input('Please insert a word')
y=reversed(x)
if x==y:
print('Is a palindrome')
else:
print('Is not a palindrome')
This always returns false because y becomes something like <reversed object at 0x00E16EF0> instead of the reversed string.
What am I being ignorant about? How would you go about coding this problem?
Try y = x[::-1]. This uses splicing to get the reverse of the string.
reversed(x) returns an iterator for looping over the characters in the string in reverse order, not a string you can directly compare to x.
reversed returns an iterator, which you can make into a string using the join method:
y = ''.join(reversed(x))
For future reference, a lambda from the answers above for quick palindrome check:
isPali = lambda num: str(num) == str(num)[::-1]
example use:
isPali(9009) #returns True
Try this code.
def pal(name):
sto_1 = []
for i in name:
sto_1.append(i)
sto_2 = []
for i in sto_1[::-1]:
sto_2.append(i)
for i in range(len(name)):
if sto_1[i] == sto_2[i]:
return "".join(sto_1), "".join(sto_2)
else:
return "no luck"
name = raw_input("Enter the word :")
print pal(name)
list(reverse( mystring )) == list( mystring )
or in the case of numbers
list(reverse( str(mystring) )) == list( str(mystring) )
Try this code:
def palindrome(string):
i = 0
while i < len(string):
if string[i] != string[(len(string) - 1) - i]:
return False
i += 1
return True
print palindrome("hannah")
Try this code to find whether original & reverse are same or not:-
if a == a[::-1]:
#this will reverse the given string, eventually will give you idea if the given string is palindrome or not.

Categories