Decorate a function to memoize results.

    Functions wraped by this decorator won't compute twice for each input.
    Any results will be stored. This decorator might increase used memory
    in order to shorten computational time.

def memoized(func):
    """Decorate a function to memoize results.

    Functions wraped by this decorator won't compute twice for each input.
    Any results will be stored. This decorator might increase used memory
    in order to shorten computational time.
    """
    cache = {}
    @wraps(func)
    def memoized_function(*args):
        """The decorated function.
        """
        try:
            return cache[args]
        except KeyError:
            value = func(*args)
            try:
                cache[args] = value
            except MemoryError:
                cache.clear()
                gc.collect()
            return value
    return memoized_function