Search code examples
pythonpython-3.xpalindrome

Leetcode problem 9. Palindrome Number (Python3). Why is my code failing?


Here is the code:

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if str(x) == reversed(str(x)):
            return True
        else: 
            return False       

The testcase where x = 121 fails - it return False as output. But it seems to me that 121 must be equal to 121 reversed. What is wrong?


Solution

  • This real issue is that reversed() returns an iterator.

    print(reversed(str(5)))
    <reversed at 0x22c166a78e0>
    

    So, you are comparing a string with an iterator thats why you are getting False.

    str(5)==reversed(str(5))
    #False
    

    This is the correct syntax:

    str(5)==''.join(reversed(str(5)))
    #True
    

    Link to document : reversed()