I’ve been working on Euler project problem 4, my code works fine but it takes too much time (0.41 seconds).How can I optimize it so that it would take less time.Is there a trick I’m missing, or special functions that I’m not aware of?
This is the code:
#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
Now that it turns out the code has < 1 s runtime, it’s not really that interesting any more. You could modify the code to test fewer numbers and give up sooner. But there’s one obvious optimization which is kind of cute. This line:
checks whether something is a palindrome each time, even if
pot <= pal. The palindrome test is expensive. If you simply swap the order: (note you don’t need the==1):then you could save a lot of time:
because
A and Bdoesn’t evaluate B ifAis already false and so it knows thatA and Bhas to be false. (This is called ‘short-circuiting’; the same thing happens with ‘A or B’ ifAis true.)Incidentally, the last line here:
doesn’t change
le. I think these three lines are meant to amount tole //= 2.