Search code examples
pythonfunctioncachingrangeassert

Python function with cache give me an error, but why?


I have the task to write a program with a function, that takes 2 integer and returns the numbers between the 2 integers. Example calc_range(3,5) -> 3,4.

The function should save the data in a cache, for the reason, that if I ask the same numbers, the function should return the cache and not go through the code again.

cache = dict()

def calc_range(lower: int, higher: int)->list:
    new_liste = []
    for i in range(lower,higher):
        if lower and higher in cache.keys():
            return cache[lower,higher]
            break            
        else:
            new_liste.append(i)
            cache[lower,higher]=new_liste
            
    return cache[lower,higher]

res_1 = calc_range(3, 5)
res_2 = calc_range(3, 5)
print(res_1)
print(res_2)
res_1 is res_2

test1

cache = dict()
res_1 = calc_range(3, 5)
res_2 = calc_range(3, 5)
assert(res_1 == [3, 4])
assert(res_1 is res_2)

test2

assert(any(cached_val is res_1 for cached_val in cache.values()))

test3

res_5 = calc_range(3, 3)
res_6 = calc_range(3, 3)
assert (res_5 == [])
assert(res_5 is res_6)

Solution

  • First check if the range is in the your cache (dictionary) if yes return it's value. If not, append all values in the range to a list and then add it to the cache (dictionary) and return the result. View the below code

    Solution

    cache = dict()
    
    def calc_range(lower: int, higher: int)->list:
        new_liste = []
        if (lower, higher) in cache:
            return cache[lower,higher]
        for i in range(lower,higher):
            new_liste.append(i)
        cache[lower,higher]=new_liste
        return cache[lower,higher]
    
    res_1 = calc_range(3, 5)
    res_2 = calc_range(3, 5)
    print(res_1)
    print(res_2)
    print(res_1 is res_2)
    

    Output

    [3, 4]
    [3, 4]
    True