For Project Euler problem 14 I wrote code that runs for longer than a minute to give the answer. After I studied about memoization, I wrote this code which runs for nearly 10 seconds on Cpython and nearly 3 seconds on PyPy. Can anyone suggest some optimization tips?
import time
d={}
c=0
def main():
global c
t=time.time()
for x in range(2,1000000):
c=0
do(x,x)
k=max(d.values())
for a,b in d.items():
if b==k:
print(a,b)
break
print(time.time()-t)
def do(num,rnum):
global d
global c
c+=1
try:
c+=d[num]-1
d[rnum]=c
return
except:
if num==1:
d[rnum]=c
return
if num%2==0:
num=num/2
do(num,rnum)
else:
num=3*num+1
do(num,rnum)
if __name__ == '__main__':
main()