memo_decorator.py
· 659 B · Python
Raw
# Factorial program with memoization using
# decorators.
# A decorator function for function 'f' passed
# as parameter
memory = {}
def memoize_factorial(f):
# This inner function has access to memory
# and 'f'
def inner(num):
if num not in memory:
memory[num] = f(num)
print('result saved in memory')
else:
print('returning result from saved memory')
return memory[num]
return inner
@memoize_factorial
def facto(num):
if num == 1:
return 1
else:
return num * facto(num-1)
print(facto(5))
print(facto(5)) # directly coming from saved memory
| 1 | |
| 2 | # Factorial program with memoization using |
| 3 | # decorators. |
| 4 | |
| 5 | # A decorator function for function 'f' passed |
| 6 | # as parameter |
| 7 | memory = {} |
| 8 | def memoize_factorial(f): |
| 9 | |
| 10 | # This inner function has access to memory |
| 11 | # and 'f' |
| 12 | def inner(num): |
| 13 | if num not in memory: |
| 14 | memory[num] = f(num) |
| 15 | print('result saved in memory') |
| 16 | else: |
| 17 | print('returning result from saved memory') |
| 18 | return memory[num] |
| 19 | |
| 20 | return inner |
| 21 | |
| 22 | @memoize_factorial |
| 23 | def facto(num): |
| 24 | if num == 1: |
| 25 | return 1 |
| 26 | else: |
| 27 | return num * facto(num-1) |
| 28 | |
| 29 | print(facto(5)) |
| 30 | print(facto(5)) # directly coming from saved memory |
| 31 |