What is memoization and how can I use it in Python?

前端 未结 13 1064
情歌与酒
情歌与酒 2020-11-21 17:25

I just started Python and I\'ve got no idea what memoization is and how to use it. Also, may I have a simplified example?

13条回答
  •  有刺的猬
    2020-11-21 18:18

    Solution that works with both positional and keyword arguments independently of order in which keyword args were passed (using inspect.getargspec):

    import inspect
    import functools
    
    def memoize(fn):
        cache = fn.cache = {}
        @functools.wraps(fn)
        def memoizer(*args, **kwargs):
            kwargs.update(dict(zip(inspect.getargspec(fn).args, args)))
            key = tuple(kwargs.get(k, None) for k in inspect.getargspec(fn).args)
            if key not in cache:
                cache[key] = fn(**kwargs)
            return cache[key]
        return memoizer
    

    Similar question: Identifying equivalent varargs function calls for memoization in Python

提交回复
热议问题