-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmemoization_using_class.py
More file actions
65 lines (50 loc) · 1.43 KB
/
memoization_using_class.py
File metadata and controls
65 lines (50 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/lib/python
# Date: 2018-02-17
#
# Description:
# Finding nth fibonacci number with and without memoization using recursion.
# Using memoization performance increases drastically.
from datetime import datetime
class Memoize(object):
"""Implements memoize functionality."""
def __init__(self, f):
"""Initializes dictionary to store factorials which can be used later.
Args:
f: Reference to called function.
"""
self.f = f
self.memo = {}
print('Calling __init__()')
def __call__(self, *args):
"""Calls the actual function if output is not stored for a input.
Args:
args: Tuple of function arguments.
"""
if args not in self.memo:
self.memo[args] = self.f(*args)
return self.memo[args]
@Memoize # This creates object of Memoize once before calling fib_memoized()
def fib_memoized(num):
if num < 2:
return num
return fib_memoized(num - 1) + fib_memoized(num - 2)
def fib(num):
if num < 2:
return num
return fib(num - 1) + fib(num - 2)
print(datetime.now())
print(fib(36))
print(datetime.now())
print(fib_memoized(36))
print(datetime.now())
# Output:
# --------------------------
# Calling __init__()
# 2018-02-17 22:19:24.541637
# 14930352
# 2018-02-17 22:19:32.679474
# 14930352
# 2018-02-17 22:19:32.679666
#
# So to find 36th fibonacci number using recursion it takes 8 seconds and on
# using memoization it provides result in less than a millisecond.