[BangPypers] python speed comparison
Emil Chacko
emilchacko at gmail.com
Mon Aug 9 12:29:27 CEST 2010
This implementation is really good.It's really fast compared to the initial
one I posted but i didn't understand much about this memoize.I asked one of
my friend he told it's python decorators.Can anyone please explain what the
function memoize does.
>
> > Readability counts. Here is my attempt.
> >
> > def memoize(f):
> > cache = {}
> > def g(a):
> > if a not in cache:
> > cache[a] = f(a)
> > return cache[a]
> > return g
> >
> > @memoize
> > def solve(n):
> > if n == 1:
> > return 1
> > elif n%2 == 0:
> > return 1 + solve(n/2)
> > else:
> > return 1 + solve(3*n+1)
> >
> > print max((solve(i), i) for i in range(1, 1+1000000))
> >
>
> >
> > $ time python p14.py
> > (525, 837799)
> >
> > real 0m3.981s
> > user 0m3.728s
> > sys 0m0.242s
> >
> > Anand
>
>
More information about the BangPypers
mailing list