Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if string is palindrome

Tags:

python

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
like image 473
Apollo Avatar asked Feb 02 '15 01:02

Apollo


People also ask

How do you determine if a string is a palindrome?

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.

How do you determine if a string is a palindrome in Java?

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.

How do you reverse a string and check if its a palindrome?

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.


Video Answer


2 Answers

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.

like image 120
Simeon Visser Avatar answered Oct 02 '22 06:10

Simeon Visser


In the second one, you need to make a str from the reversed type instance -- it's not hard:

if string == ''.join(reversed(string)):
like image 23
Alex Martelli Avatar answered Oct 02 '22 05:10

Alex Martelli