-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfibo.py
More file actions
71 lines (58 loc) · 1.59 KB
/
fibo.py
File metadata and controls
71 lines (58 loc) · 1.59 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
66
67
68
69
70
71
#!bin/python2.7
"""
CS212 Udacity Design of computer Programs
Module 3 - Problem 4
Cache Memoization
"""
#from re_api import decorator
from functools import update_wrapper
def decorator(d):
"""Make function d a decorator; d wraps a function fn.
Updates help of both the fn d and the fn that d is applied to."""
def _d(fn):
return update_wrapper(d(fn), d)
return update_wrapper(_d, d)
@decorator
def memo(f):
"""Decorator that catches the return value of each call to f(args).
Then when called again with same args, we can just look it up."""
cache = {}
def _f(*args):
try:
cache[args]
except KeyError:
cache[args] = result = f(*args)
return result
except TypeError:
return f(*args)
return _f
@decorator
def countcalls(f):
"Decorator that makes the function countcalls to it, in countcalls[f]."
def _f(*args):
callcounts[_f] += 1
return f(*args)
callcounts[_f] = 0
return _f
callcounts = {}
@countcalls
@memo
def fib(n): return 1 if n <= 1 else fib(n-1) + fib(n-2)
@decorator
def trace(f):
indent = ' '
def _f(*args):
signature = '%s(%s)' % (f.__name__, ', '.join(map(repr, args)))
print '%s--> %s' % (trace.level*indent, signature)
trace.level += 1
try:
result = f(*args)
print '%s<-- %s === %s' % ((trace.level-1)*indent, signature, result)
finally:
trace.level -= 1
return result
trace.level = 0
return _f
def disabled(f): return f
a = fib(5)
print a