Created
March 14, 2019 19:54
-
-
Save davidbody/9214437466f4fa56b38e7d7a31efb285 to your computer and use it in GitHub Desktop.
TDD Fibonaci numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def memoize(func): | |
cache = {} | |
def wrapper(n): | |
if not n in cache: | |
cache[n] = func(n) | |
return cache[n] | |
return wrapper | |
@memoize | |
def fib(num): | |
if num == 0: | |
return 0 | |
if num <= 2: | |
return 1 | |
else: | |
return fib(num - 1) + fib(num - 2) | |
def fib_loop(num): | |
x = 0 | |
y = 1 | |
result = 0 | |
if(num == 1): | |
return 1 | |
i = 1 | |
while (i < num): | |
result = x + y | |
x = y | |
y = result | |
i = i + 1 | |
return result | |
def test_fib0(): | |
assert fib(0) == 0 | |
def test_fib1(): | |
assert fib(1) == 1 | |
def test_fib2(): | |
assert fib(2) == 1 | |
def test_fib3(): | |
assert fib(3) == 2 | |
def test_fib4(): | |
assert fib(4) == 3 | |
def test_fib12(): | |
assert fib(12) == 144 | |
def test_fib15(): | |
assert fib(15) == 610 | |
def test_fib40(): | |
assert fib(40) == 102334155 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment