Assuming that cache is a dictionary, you can make a tuple from the other parameters and see whether that tuple is in the dict. If it is, return the value from the dict, otherwise calculate the value and store it in the dict before returning it. You might also provide a default value for cache so the function can also be used without it.
def one_range(lower, higher, cache=None): if cache is not None and (lower, higher) in cache: return cache[(lower, higher)] lst = [] for i in range(lower,higher): lst.append(i) if cache is not None: cache[(lower, higher)] = lst return lst
Example:
c = {} x = one_range(2, 4, c) y = one_range(1, 4, c) z = one_range(2, 4, c) print(x is z) # True print(c) # {(2, 4): [2, 3], (1, 4): [1, 2, 3]}
That's a lot of boiler plate code, though, cluttering the function. In practice, this can be done much easier with a function decorator. If you can not use functools.lru_cache, you can implement your own memoization decorator in just a few lines of code:
def memo(f): f.cache = {} def _f(*args, **kwargs): if args not in f.cache: f.cache[args] = f(*args, **kwargs) return f.cache[args] return _f
Then use it on your function, without the no longer needed cache parameter:
@memo def one_range(lower, higher): lst = [] for i in range(lower,higher): lst.append(i) return lst
range. You won't be able to call the originalrangefrom inside it...listtoo...