如何优化python代码:Euler projec prob 4

2024-10-03 17:23:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在研究Euler project problem 4,我的代码运行得很好,但它花费了太多的时间(0.41秒),我如何优化它,使它花费更少的时间时间。是有什么诀窍我没有,或是我不知道的特殊功能?
代码如下:

#Note: tpal is a function to test if number is palindrome

pal =0

for i in range(999,100,-1):
    if pal >= i*999:    #A way to get out of loop and to not test on all numbers
        break 
    for j in range(999,100,-1):
        if pal >= i*999:
            break 
        if j > i:                         #numbers would already have been tested so I skip them 
            continue
        pot=i*j
        if ((tpal(pot)==1)and(pot> pal)):
            pal=pot
            i1=i
            j1=j

print(i1,j1,pal)

def tpal(num):
    num=list(str(num))
    Le=len(num)
    if Le == 1: # if number is of one digit than palindrome
        return 1

    le=len(num)

    if le%2 !=0: #4 example 10101even nbr
        le-=1
    le/2    

    for i in range(0,le):
       if num[i]!=num[Le-i-1]:
           return 0

    return 1                  

Tags: toinleforreturnifis时间
3条回答

没有给你完整的答案。这里有一些指针。在

  • 重新考虑你的for循环,它们会使事情变得复杂。也许内部循环应该从i开始?在
  • 删除所有那些愚蠢的句子,如果你的循环是正确的,你不需要它们。在
  • 最后,int(str(pot)[::-1])==pot那么它是一个回文

编辑: 让他/她自己解决问题。无需在此处发布解决方案。在

既然代码已经有了<;1s运行时,就不再那么有趣了。你可以修改代码来测试更少的数字,并且更快地放弃。但有一个明显的优化是很可爱的。这条线:

        if ((tpal(pot)==1)and(pot> pal)):

每次检查某个内容是否为回文,即使pot <= pal。回文测试是昂贵的。如果您只需交换顺序:(请注意,您不需要==1):

^{pr2}$

这样可以节省大量时间:

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

如果cd3{cd3}是错的,那么它就知道了。(这称为“短路”;如果A为真,则“A或B”也会发生同样的情况。)

顺便说一下,最后一行:

if le%2 !=0: #4 example 10101even nbr
    le-=1
le/2    
^^^^

不会改变le。我想这三行应该是le //= 2。在

试试这个,不会花31秒的时间:

def isPalindrome(n):
    return str(n) == str(n)[::-1]

def listNums():
    a, b, pal = 0, 0, 0;
    for i in range(999, 99, -1):
        for j in range(999, 99, -1):
            n = i * j
            if isPalindrome(n) and n > pal:  # better to use "n > pal and isPalindrome(n)" instead, see other answer for details.
                a, b, pal = i, j, n
    return a, b, pal             

print listNums()

运行此操作大约需要1秒。对于这样的东西,你当然不需要在循环中使用那些多余的if语句——如果你循环,比如说,range(9999, 999, -1),你可以考虑做一些类似的优化(当然,有很多潜在的优化可以对类似的东西进行,例如,不要在每个i,j对中循环两次)。在

相关问题 更多 >