I wrote two simple functions to determine if a string is a palindrome. I thought they were equivalent, but 2 doesn't work. Why is this?
1
def is_palindrome(string):
if string == string[::-1]:
return True
else:
return False
2
def is_palindrome(string):
if string == reversed(string):
return True
else:
return False
If the string is made of no letters or just one letter, it is a palindrome. Otherwise, compare the first and last letters of the string. Otherwise, the first and last letters are the same. Strip them from the string, and determine whether the string that remains is a palindrome.
Solution approach We can use the isPalindrome() function to check if a string is a palindrome. We pass our input string as an argument and the function will return true if the string is a palindrome and false otherwise.
The easiest way to find if a given String is Palindrome or not is by writing a recursive function to reverse the String first and then comparing the given String with the reversed String, if both are equal then the given String is a palindrome.
reversed
doesn't create a string but a 'reversed' object:
>>> reversed('radar')
<reversed object at 0x1102f99d0>
As such, the string 'radar'
does not compare equal to the object reversed('radar')
. To make it work, you need to make sure the reversed
object is actually evaluated:
def is_palindrome(string):
if string == u''.join(reversed(string)):
return True
else:
return False
The u''.join(reversed(string))
inserts u''
in between each of the characters in the string and this leads to the reversed string being turned into a string object.
In the second one, you need to make a str
from the reversed
type instance -- it's not hard:
if string == ''.join(reversed(string)):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With