Last active 1728394071

On fait de la mémoization avec un décorateur

nithir's Avatar nithir revised this gist 1728394071. Go to revision

1 file changed, 1 deletion

memo_decorator.py

@@ -1,4 +1,3 @@
1 -
2 1 # Factorial program with memoization using
3 2 # decorators.
4 3

nithir's Avatar nithir revised this gist 1728392474. Go to revision

No changes

nithir's Avatar nithir revised this gist 1728392462. Go to revision

1 file changed, 30 insertions

memo_decorator.py(file created)

@@ -0,0 +1,30 @@
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
Newer Older