擅长:python、mysql、java
<p>既然代码已经有了<;1s运行时,就不再那么有趣了。你可以修改代码来测试更少的数字,并且更快地放弃。但有一个明显的优化是很可爱的。这条线:</p>
<pre><code> if ((tpal(pot)==1)and(pot> pal)):
</code></pre>
<p>每次检查某个内容是否为回文,即使<code>pot <= pal</code>。回文测试是昂贵的。如果您只需交换顺序:(请注意,您不需要<code>==1</code>):</p>
^{pr2}$
<p>这样可以节省大量时间:</p>
<pre><code>In [24]: timeit orig()
1 loops, best of 3: 201 ms per loop
In [25]: timeit orig_swapped()
10 loops, best of 3: 30.1 ms per loop
</code></pre>
<p>如果cd3{cd3}是错的,那么它就知道了。(这称为“短路”;如果<code>A</code>为真,则“A或B”也会发生同样的情况。)</p>
<p>顺便说一下,最后一行:</p>
<pre><code>if le%2 !=0: #4 example 10101even nbr
le-=1
le/2
^^^^
</code></pre>
<p>不会改变<code>le</code>。我想这三行应该是<code>le //= 2</code>。在</p>