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

前端 未结 13 1177
情歌与酒
情歌与酒 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:22

    Here is a solution that will work with list or dict type arguments without whining:

    def memoize(fn):
        """returns a memoized version of any function that can be called
        with the same list of arguments.
        Usage: foo = memoize(foo)"""
    
        def handle_item(x):
            if isinstance(x, dict):
                return make_tuple(sorted(x.items()))
            elif hasattr(x, '__iter__'):
                return make_tuple(x)
            else:
                return x
    
        def make_tuple(L):
            return tuple(handle_item(x) for x in L)
    
        def foo(*args, **kwargs):
            items_cache = make_tuple(sorted(kwargs.items()))
            args_cache = make_tuple(args)
            if (args_cache, items_cache) not in foo.past_calls:
                foo.past_calls[(args_cache, items_cache)] = fn(*args,**kwargs)
            return foo.past_calls[(args_cache, items_cache)]
        foo.past_calls = {}
        foo.__name__ = 'memoized_' + fn.__name__
        return foo
    

    Note that this approach can be naturally extended to any object by implementing your own hash function as a special case in handle_item. For example, to make this approach work for a function that takes a set as an input argument, you could add to handle_item:

    if is_instance(x, set):
        return make_tuple(sorted(list(x)))
    
    0 讨论(0)
提交回复
热议问题