palindromes of sums less than 30, help to optimize my code
<p>On my way of studying Python i stacked on the problem:<br><br>
I have to count all numbers from <b>0</b> to <b>130000</b> which are palindromes, but they should be palindromes after sum of the number and its reversed version. For example: 
<br> <code>i</code> = 93 
<br>93 + 39 = 132
<br>132 + 231 = 363
<br><code>count_of_palindromes</code> should count all <code>i</code> which are palindromes after <b>1</b> or more iterations of summing, but less than <b>50</b>.
<br>I've already written the code but it's too way difficult to run on my PC, Python stops responding :( 
<br><br>Any advices how to optimize my code?</p>

<pre><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 &lt;= 50:
                    while (sum == int(str(sum)[::-1])) != True:
                        trying += 1
                        sum += int(str(sum)[::-1])                
                    if trying &gt; 0 and trying &lt;= 50:
                        count_of_palindromes += 1
                        break
        print(count_of_palindromes)
</code></pre>

<p>Thank you very much!</p>

<p>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.</p>

<pre><code>def reverse(n):
    return int(str(n)[::-1])

def is_palindrome(n):
    return n == reverse(n)
</code></pre>

<p>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</p>

<pre><code>count_of_palindromes = 0
for i in range(130000):
    for tries in range(50):
        if(is_palindrome(i)):
            counter += 1
            break
        else:
            i = i + reverse(i)
print(count_of_palindromes)
</code></pre>

<p>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</p>

python optimization