我一直在研究 Euler 项目问题 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