Skip to content

Commit 7b4b290

Browse files
committed
Modernize code, add @cache example
1 parent f43dea4 commit 7b4b290

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

source-code/decorators/memoize.py

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#!/usr/bin/env python
22

3-
from functools import lru_cache
3+
from functools import cache, lru_cache
44

55

66
def memoize(f):
@@ -30,24 +30,32 @@ def fib_lru_cache(n):
3030
return fib_lru_cache(n - 1) + fib_lru_cache(n - 2)
3131

3232

33+
@cache
34+
def fib_cache(n):
35+
if n < 2:
36+
return 1
37+
else:
38+
return fib_cache(n - 1) + fib_cache(n - 2)
39+
40+
3341
def fib(n):
3442
if n < 2:
3543
return 1
3644
else:
3745
return fib(n - 1) + fib(n - 2)
3846

3947

40-
def execute(func, n_max):
48+
def execute(func, n_max, verbose=False):
4149
values = []
4250
start = datetime.now()
4351
for n in range(n_max):
4452
values.append(func(n))
4553
delta = datetime.now() - start
46-
for n in range(n_max):
47-
print('{0}({1}) = {2}'.format(func.__name__, n, values[n]))
48-
delta_time = float(delta.seconds) + 1.0e-6*float(delta.microseconds)
49-
print('{0}: {1:.6f} s'.format(func.__name__, delta_time))
50-
return delta_time
54+
if verbose:
55+
for n in range(n_max):
56+
print('{0}({1}) = {2}'.format(func.__name__, n, values[n]))
57+
return float(delta.seconds) + 1.0e-6*float(delta.microseconds)
58+
5159

5260
if __name__ == '__main__':
5361
from argparse import ArgumentParser
@@ -56,10 +64,9 @@ def execute(func, n_max):
5664
arg_parser = ArgumentParser(description='compare memoized versus '
5765
'non-memooized')
5866
arg_parser.add_argument('n_max', type=int, help='maximum n value')
67+
arg_parser.add_argument('--verbose', action='store_true',
68+
help='display computed values')
5969
options = arg_parser.parse_args()
60-
delta_fib = execute(fib, options.n_max)
61-
delta_fib_memoized = execute(fib_memoized, options.n_max)
62-
delta_fib_lru_cache = execute(fib_lru_cache, options.n_max)
63-
print('non-memoized:\t\t{0:.6f} s'.format(delta_fib))
64-
print('memoized:\t\t{0:.6f} s'.format(delta_fib_memoized))
65-
print('lru_cache:\t\t{0:.6f} s'.format(delta_fib_lru_cache))
70+
for fib_impl in (fib, fib_memoized, fib_cache, fib_lru_cache):
71+
delta_time = execute(fib_impl, options.n_max, options.verbose)
72+
print(f'{fib_impl.__name__:20s}: {delta_time:.6f} s')

0 commit comments

Comments
 (0)