Check for a palindrome in python - python

palindrome
Here is the code i have written so far:
string=input(("Enter a string:"))
for char in string:
print(char)
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("Not a palindrome")

To produce the described output, it looks like you'd need to perform character-wise comparison. What you've attempted is a straight-forward comparison of a string with it's reverse. Try this:
string=input(("Enter a string:"))
rev_string = string[::-1]
for i in range(len(string)):
print (string[i], "--", rev_string[i])
if string[i].lower() != rev_string[i].lower():
print("Not a palindrome")
exit(0)
print("The string is a palindrome")

I would like to point out that checking if two characters are the same is not trivial, as discussed in this answer. The following code should work for any character:
import unicodedata
def normalize_caseless(text):
return unicodedata.normalize("NFKD", text.casefold())
def caseless_equal(left, right):
return normalize_caseless(left) == normalize_caseless(right)
string = input("Enter a string: ")
rev_string = string[::-1]
i = 0
palindrome = True
while palindrome and i < len(string):
print(f'{string[i]} -- {rev_string[i]}')
palindrome = caseless_equal(string[i], rev_string[i])
i += 1
print(f"The string is{' not'*(not palindrome)} a palindrome")

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 get my code to repeat in a loop?

str = input("Enter the String")
l = len(str)
p = l-1
index = 0
while index < p:
if str[index] == str[p]:
index = index + 1
p = p-1
print("String is a Palindrome")
break
else:
print("String is not a Palindrome")
break
i need this to be able to ask the user if they would like to repeat the process or not but i cant figure it out because every time i try it only repeats the string "string is not a palindrome"
Are you looking for this:
while True:
user_input = input("Enter the String")
l = len(user_input)
p = l-1
index = 0
while index < p:
if user_input[index] == user_input[p]:
index = index + 1
p = p-1
print("String is a Palindrome")
break
else:
print("String is not a Palindrome")
break
gonext = input("continue?(no to exit) ")
if gonext == "no":
break
elif gonext == "yes":
continue
add a input and if statement to ask the user, and while True to repeat.
and str is a built-in from Python, so don't use it as variable name.
If you want your code to be able to repeat any task, you need to wrap it into a loop. Also you shouldn't use str as a name for a variable, because that name is used in python to create a new string.
one possible solution would be
repeat = True
while repeat:
# your code
repeat = input("repeat? (y for yes, everything else is tretaed as no)\n") == "y"
Further, I want to point out, that your code is not doing what you expect.
A palindrome is defined as a String which reads backwards the same as forwards.
In your code, you are actually just testing whether the first and last character are the same. In the if branch, the problem is not solved. The positive result can only be given at the end of the loop.
Also, you don't cover the empty string (no output at all), which I would consider as a palindrome.
some cases you could test:
ada -> correct positive
asd -> correct negative
asda -> false positive
"" -> nothing at all
-a[arbitray string]a -> positive?
A correct implementation of the palindrome check would be something like this:
user_input = input("Enter the String\n")
isPalindrome = True
for i in range(len(user_input)//2): # check till center from both ends
if user_input[i] != user_input[-i-1]: # index -1 is last character
isPalindrome = False
break
if isPalindrome:
print("String is a Palindrome")
else:
print("String is not a Palindrome")

Palindrome logic in python: What is wrong with this program?

def isPalindrome(word):
l = len(word)
for i in range(l/2):
if(word[i] != word[i+l-1]):
return 0
return 1
def main():
print("\n\n\tTo Check if the word is a Palindrome\n\n")
word = raw_input("Enter a word : ")
if(isPalindrome(word) == 1):
print("It is a Palindrome")
elif:
print("It is not a Palindrome")
main()
In my opinion everything is right in the program. It goes good when I enter a word which is not a palindrome but when I enter a palindrome it gives an error like this:
Enter a word : madam
Traceback (most recent call last):
File "temp.py", line 16, in <module>
File "temp.py", line 6, in isPalindrome
IndexError: string index out of range
First thing that is wrong is: elif: - if you're using else-if you should provide a condition, the fix in this case it to change it to else:
Second, the if should be: if(word[i] != word[l-i-1]): in order for the function to work (check that each letter is equal to its equivalent in the word).
Third, less critical but still important: keep the styling:
remove redundant braces
use proper naming convention (snake-case - not camel-case)
use True/False as return values instead of 1/0
use floor division // (as AChampion mentioned in the comments)
Complete code (fixed):
def is_palindrome(word):
l = len(word)
for i in range(l//2):
if word[i] != word[l-i-1]:
return False
return True
def main():
print("\n\n\tTo Check if the word is a Palindrome\n\n")
word = raw_input("Enter a word : ")
if is_palindrome(word):
print("It is a Palindrome")
else:
print("It is not a Palindrome")
if __name__ == "__main__":
main()
Your logic for checking palindrome should be:
if(word[i] != word[l-1-i]):
return 0
It's okay to do l/2 if you're on python 2 but python 3 will produce the result as a floating point value.
Your code seems to be in py3.
And you need to give a condition to the elif block. Otherwise, change it to else.
Change word[i+l-1] to word[l-i-1]:
def isPalindrome(word):
l = len(word)
for i in range(l // 2):
if(word[i] != word[l-i-1]):
return 0
return 1
The goal is to get the word[l-i-1 to count down while i is counting up; hence, you need to subtract i rather than add it.
Also, I would change the l/2 to l // 2 so that it works in Python 3 as well.
Hope that helps :-)
You should round the l/2 value
def isPalindrome(word):
l = len(word)
for i in range(round(l/2)):
if(word[i] != word[i+l-1]):
return 0
return 1
print("\n\n\tTo Check if the word is a Palindrome\n\n")
word = input("Enter a word : ")
if(isPalindrome(word) == 1):
print("It is a Palindrome")
else:
print("It is not a Palindrome")

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?
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

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

Categories