Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented memoize in python. #1

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions JavaScript/2-speed.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
const LOOP = 10000;

function memoize(fn) {
const cache = {};
const cache = new Map();
return (...args) => {
const key = args + '';
const val = cache[key];
if (val) return val;
if (cache.has(key)) {
return cache.get(key);
}
else {
const res = fn(...args);
cache[key] = res;
cache.set(key, res);
return res;
}
};
Expand All @@ -20,14 +21,21 @@ let fib = n => (n <= 2) ? 1 : fib(n - 1) + fib(n - 2);

function speedTest(name, fn, args, count) {
let start = new Date().getTime();
for (let i = 0; i < count; i++) {
let i; //or use "var" in for(...). (no)
for (i = 0; i < count; i++) {
fn(...args);
}
let end = new Date().getTime();
let time = end - start;
console.log(`${name} * ${count} : ${time}`);
}

speedTest('fib(10)', fib, [10], LOOP);
speedTest('fib(15)', fib, [15], LOOP);
speedTest('fib(20)', fib, [20], LOOP);
speedTest('fib(25)', fib, [25], LOOP);
fib = memoize(fib);
speedTest('memoized fib(10)', fib, [10], LOOP);
speedTest('memoized fib(15)', fib, [15], LOOP);
speedTest('memoized fib(20)', fib, [20], LOOP);
speedTest('memoized fib(25)', fib, [25], LOOP);
15 changes: 15 additions & 0 deletions Python/1-fibonacci-simple.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)

print('fib(0): ', fib(0))
print('fib(1): ', fib(1))
print('fib(3): ', fib(3))
print('fib(7): ', fib(7))
print('fib(10): ', fib(10))

print('fib(40): ', fib(40)) # here is a problem
20 changes: 20 additions & 0 deletions Python/2-fibonacci-memoize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
def memoize(f):
cache = {}
def inMemo(x):
if x not in cache:
cache[x] = f(x)
return cache[x]
return inMemo


def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)


fib = memoize(fib)
print('fib(40): ', fib(40))
20 changes: 20 additions & 0 deletions Python/3-fibonacci-decorator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
def memoize(f):
cache = {}
def inMemo(x):
if x not in cache:
cache[x] = f(x)
return cache[x]
return inMemo


@memoize
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)


print('fib(40): ', fib(40))
26 changes: 26 additions & 0 deletions Python/4-fibonacci-class.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class Memoize:
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
if args not in self.cache:
self.cache[args] = self.func(*args)
return self.cache[args]

@Memoize
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)


print('fib(0): ', fib(0))
print('fib(1): ', fib(1))
print('fib(3): ', fib(3))
print('fib(7): ', fib(7))
print('fib(10): ', fib(10))

print('fib(40): ', fib(40))
34 changes: 34 additions & 0 deletions Python/5-memoize-file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import os, pickle
from functools import wraps

def memoize(fn):
if os.path.exists('memoize.pkl'):
print('Reading cache file!')
with open('memoize.pkl') as f:
cache = pickle.load(f)
else:
cache = {}

@wraps(fn)
def wrap(*args):
if args not in cache:
print('Running function with argument', args[0])
cache[args] = fn(*args)
# update the cache file
with open('memoize.pkl', 'wb') as f:
pickle.dump(cache, f)
else:
print('Result in cache!')
return cache[args]
return wrap

@memoize
def sqrt(x):
return x**2


print(sqrt(5))
print(sqrt(5))
print(sqrt(7))
print(sqrt(5))
print(sqrt(7))
13 changes: 13 additions & 0 deletions Python/6-memoize-lru.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import functools

@functools.lru_cache()
def fib_lru(n):
if n in (0, 1):
return n
else:
return fib_lru(n - 2) + fib_lru(n - 1)

print('fib_lru(0): ', fib_lru(0))
print('fib_lru(7): ', fib_lru(7))
print('fib_lru(10): ', fib_lru(10))
print('fib_lru(40): ', fib_lru(40))
Binary file added Python/memoize.pkl
Binary file not shown.