Valery Danilik Valery Danilik - 8 months ago 35
Python Question

palindromes of sums less than 30, help to optimize my code

On my way of studying Python i stacked on the problem:

I have to count all numbers from 0 to 130000 which are palindromes, but they should be palindromes after sum of the number and its reversed version. For example:

= 93

93 + 39 = 132

132 + 231 = 363

should count all
which are palindromes after 1 or more iterations of summing, but less than 50.

I've already written the code but it's too way difficult to run on my PC, Python stops responding :(

Any advices how to optimize my code?

count_of_palindromes = 0
for i in range(0,130000):
trying = 0
if (i == int(str(i)[::-1])) != True:
trying += 1
sum = i + int(str(i)[::-1])
while trying <= 50:
while (sum == int(str(sum)[::-1])) != True:
trying += 1
sum += int(str(sum)[::-1])
if trying > 0 and trying <= 50:
count_of_palindromes += 1

Thank you very much!


Let's tidy your code up a bit first for readability. We'll just take some of the syntax heavy string stuff and encapsulate it.

def reverse(n):
    return int(str(n)[::-1])

def is_palindrome(n):
    return n == reverse(n)

That's better. I think your problem is the second nested while loop. It runs until it finds a palindrome, then checks if it found it in the first fifty tries. You want it to run up to fifty times, then give up. I think the best way would be a second for loop

count_of_palindromes = 0
for i in range(130000):
    for tries in range(50):
            counter += 1
            i = i + reverse(i)

There are some more ways of speeding this up by avoiding string operations and replacing them with math, but that's overkill for this. I was a little unclear on how your problem wants you to treat natural palindromes, so you may need to modify this solution