Python Code running into indexing problem, please help!

  • 0
    class Solution:
        # @return a boolean
        def isPalindrome(self, x):
            #negative numbers are not palindromes, return 0
            if x<0:
                return 0
            #making sure the length is greater than 1, otherwise it's always a palindrome
            while len(x)>1:
                #check the first and last digits to see if they are equal
                while x[0]==x[len(str(x))-1]:
                    #if yes, take out those digits, repeat the process until there's only 1 digit left
                    #if there's only one or no digit left after repeatedly taking out digits, it's a palindrome
                    if len(x)==1 | len(x)==0:
                        return 1
                #if the first and last digits do not equal to each other, return 0 as it's not a palindrome
                    return 0
                return 1

    Since the definition states that negative numbers are not palindromes, I only cared about non-negatives. I do it by repeatedly taking out first and last digits of a string (after converting and replacing the original input, thus no extra space) until there's only 1 or no digit left. If that happens, it's a palindrome.

    However, I run into Index error when executing. Is it because that once a string has no digit, it cannot be indexed (as len(x) will not return an answer)?

  • 0

    Bug :

    if len(x)==1 | len(x)==0:

    should be :

    if len(x)==1 or len(x)==0:

    Your were using the bit-wise OR operator with higher presidence.
    With the absense of parantheses it translate into following expression:

      len(x)== (1 or len(x)) == 0

    Note that python allows expressions like 5 >= x >= 10 which can be very handy compared to C/Java equivalent checks
    but in this case it turned your your expression into very hard to spot bug!

    so when a single digit or empty. It checks 1==1==0 => False or 0==1==0 =>False And you get blown-up at test
    x[0]==x[len(str(x))-1] or next iteration which makes your x='' if it was a single digit.

    Additonal note: since x=str(x) string already x[0]==x[len(str(x))-1] can be x[0]==x[len(x)-1] or better yet x[0]==x[-1]
    Similarly x=x[1:len(x)-1] can be x=[1:-1]

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.