-
Notifications
You must be signed in to change notification settings - Fork 0
/
fibs.py
58 lines (49 loc) · 1.37 KB
/
fibs.py
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
"""
Author: Leigh Stauffer
Project: 3
File Name: fibs.py
Two versions of the functions to compute the nth Fibonacci number.
"""
from tools import Counter
def fib1(n, counter = None):
"""The standard recursive version."""
if counter:
counter.increment()
if n == 1 or n == 2:
return 1
else:
return fib1(n - 1, counter) + fib1(n - 2, counter)
def fib2(n, counter = None):
"""The recursive version with a memoizing cache."""
cache = dict()
def fastFib(n):
if counter:
counter.increment()
if n == 1 or n == 2:
return 1
elif n in cache:
return cache[n]
else:
value = fastFib(n - 1) + fastFib(n - 2)
cache[n] = value
return value
return fastFib(n)
def test(fib):
"""Runs some tests on a fib function."""
for n in range(1, 6):
print("n:", n, "fib(n):", fib(n))
def testWithCounter(fib):
"""Runs some tests on a fib function."""
counter = Counter()
for n in range(1, 11):
counter.reset()
print("n:", n, "fib(n):", fib(n, counter),
" Number of calls:", str(counter))
def main():
"""To test, pass the name of the fib function to test."""
## test(fib1)
## test(fib2)
## testWithCounter(fib1)
testWithCounter(fib2)
if __name__ == "__main__":
main()