Dictionary

def compute(n):
*# Check the cache.*
if n in cache:
return cache[n]
*# Do a computation.*
if n > 10:
n = 10
v = n ** n
if v > 1000:
v /= 2
*# Store the result.*
cache[n] = v
return v
*# Cache is a dictionary.*
cache = {}
*# Test.*
print(compute(1))
print(compute(2))
print(compute(3))
print(compute(4))
print(compute(5))
print(compute(6))
print(compute(7))
print(compute(8))
print(compute(9))
print(compute(10))
*# These use the cache.*
print(compute(1))
print(compute(2))
print(compute(3))
print(compute(4))
print(compute(5))1
4
27
256
1562.5
23328.0
411771.5
8388608.0
193710244.5
5000000000.0
1
4
27
256
1562.5

import functools
@functools.lru_cache(maxsize=12)
def compute(n):
*# We can test the cache with a print statement.*
if n > 10:
n = 10
v = n ** n
if v > 1000:
v /= 2
return v
*# Fill up the cache.*
print(compute(1))
print(compute(2))
print(compute(3))
print(compute(4))
print(compute(5))
*# Cache is hit now.*
print(compute(1))
print(compute(2))
print(compute(3))
print(compute(4))
print(compute(5))1
4
27
256
1562.5
1
4
27
256
1562.5

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

This page was last updated on Sep 16, 2022 (edit link).