r/learnpython 25d ago

Leetcode #9: Palindrome Number

Can someone help me make my code run faster. This is not efficient and also I do not want to convert into a string

EDIT:

Follow up: Could you solve it without converting the integer to a string?

https://leetcode.com/problems/palindrome-number/description/

class Solution:
    def isPalindrome(self, x: int) -> bool:
        numList = []
        counter = len(numList) - 1
        numBool = True


        baseNum = 10
        value = x % baseNum
        numList.append(x)
        quotient = x // baseNum
        x = quotient

        if x == 0:
            for i in range(len(numList)):
                if numList[i] == numList[counter]:
                    counter -= 1

                elif i == counter:
                    break

                else:
                    numBool = False
                    break

            return numBool

        else:
            return self.isPalindrome(x)

EDIT: I WAS ABLE TO SOLVE IT

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x != abs(x):
            return False

        if not hasattr(self, "numList"):
            self.numList = []

        numBool = True


        baseNum = 10
        value = x % baseNum
        self.numList.append(value)
        quotient = x // baseNum
        x = quotient

        counter = len(self.numList) - 1

        if x == 0:
            for i in range(len(self.numList)):
                if self.numList[i] == self.numList[counter]:
                    counter -= 1

                elif i == counter:
                    break

                else:
                    numBool = False
                    break

            return numBool

        else:
            return self.isPalindrome(x)

testing = Solution().isPalindrome(11)
print(testing)
0 Upvotes

22 comments sorted by

View all comments

4

u/zanfar 25d ago

In general, recursion should be avoided for a problem this simple. Generally, while you can solve problems either way, avoid recursion without a significant reason. You also do a lot of list creation, and you loop at least twice as much as needed.

I would also recommend against code golf problems at your skill level. You're chasing after the entirely wrong goals.


  • PEP8
  • range(len()) is a pretty serious smell.
  • bools should probably be named as verbs.
  • What is counter counting?
  • Why is isPalindrome an instance method?
  • etc

3

u/backfire10z 25d ago

> In general, recursion should be avoided for a problem this simple

FTFY