Steven D'Aprano <[EMAIL PROTECTED]> writes:
> def factorial(n, _cache={}):
>     try:
>        return _cache[n]
>     except KeyError:
> There are other ways of implementing caches, but this is quick and easy
> and works well for many functions.

I like this better (examples are untested):

    def factorial(n):
       try:
          return factorial.cache[n]
       except KeyError: pass
       ...
    factorial.cache = {}

you could even use a decorator:

    def memoize(f):  # memoize a 1-arg function
       f.cache = {}
       def g(f,x):
          if x in f.cache: return f.cache[x]
          return f.cache.setdefault(x, f(x))
       return functools.partial(g,f)
    ...

    @memoize
    def factorial(n):
       return 1 if n==0 else n*factorial(n-1)
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to