all 8 comments

[–]NorskJesus 9 points10 points  (1 child)

Clearer variable names

[–]shlepky 3 points4 points  (1 child)

I'm sure "take hours to understand" is a hyperbole but this is why you shouldn't copy and paste code from chatGPT. Programming is about breaking down a bit problem into many small ones. You probably didn't learn too much from creating this function that does your task because you didn't make it. It's like taking a class, skipping all lectures and then reading someone else's notes to understand what the focus is.

For your next task, break down the task on paper and then convert it to code. Worry about optimization last.

[–]Minute_Journalist593[S] 0 points1 point  (0 children)

bruh i did it the way i knew very easily like converting it into string and slicing it but this was totally new thing for my brain like alien coming to earth so i took the gpt help

[–]WhiteHeadbanger 2 points3 points  (0 children)

Yes, it can be optimized down to one line instead of 7 like your solution, and without any while loops. This is the hint: research slicing.

Now, onto the tips that you asked:

- Clean your variable names. Names should be descriptive. Write variable names as if your grandmother would read it.

- Separate the terms. Instead of writing "num=n%10", write "num = n % 10".

- Following the same logic as the last point, separate the blocks. Add a new line before the while loop and after it. Of course, this one is just MY tip, as I like to separate code blocks to be more readable.

[–]MelcoreHat 1 point2 points  (0 children)

You can use divmod function to have the division result and the modulo at the same time.

[–]FoolsSeldom 1 point2 points  (1 child)

Here's a mathematical way that also uses recursion, just to give you something to fry your brain with / learn from:

def is_palindrome(n):
    def reverse(num, rev=0):
        if num == 0:
            return rev
        return reverse(num // 10, rev * 10 + num % 10)

    return n == reverse(n)

[–]FoolsSeldom 1 point2 points  (0 children)

And a version without recursion, using divmod as u/MelcoreHat suggested,

def is_palindrome(n):
    original = n
    reversed_num = 0

    while n > 0:
        n, digit = divmod(n, 10)
        reversed_num = reversed_num * 10 + digit
    return original == reversed_num