我一直在研究Euler project problem 4,我的代碼工作正常,但它需要很多時間(0.41秒)。我怎樣才能優化它,這樣會花費更少的時間。有沒有我錯過的技巧,或者我不知道的特殊功能?
這是代碼:我該如何優化Python代碼:歐拉項目概述4
#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
至少,你可以用j = i開始內部循環。 – sshannin
31秒?有些事情是非常非常錯誤的。你的代碼對我來說需要0.1s,而且即使是一個完全沒有優化的1線程也只需要0.8s。你的'tpal'函數是什麼樣的? – DSM
輸出結果應該是什麼? – arshajii