diff --git a/algorithms/fibonacci/fibonacci.py b/algorithms/fibonacci/fibonacci.py new file mode 100755 index 0000000..7cdf480 --- /dev/null +++ b/algorithms/fibonacci/fibonacci.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 +# this shows the fibonacci sequence with basic recursion. +# note that it gets very slow at the end due to the recursion + + +def fibonacci(n): + if n == 1: + return 1 + elif n == 2: + return 1 + elif n > 2: + return fibonacci(n-1) + fibonacci(n-2) + + +for n in range(1, 101): + print(n, ":", fibonacci(n)) diff --git a/algorithms/fibonacci/fibonacci_with_cache.py b/algorithms/fibonacci/fibonacci_with_cache.py new file mode 100755 index 0000000..4519b07 --- /dev/null +++ b/algorithms/fibonacci/fibonacci_with_cache.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +# this introduces recursive fibonacci with a cache of recent function calls +# this is introducing memoization: caching recent function call results + +fibonacci_cache = {} + + +def fibonacci(n): + # If we have cached the value, then return it + if n in fibonacci_cache: + return fibonacci_cache[n] + + # compute nth term + if n == 1: + value = 1 + elif n == 2: + value = 1 + elif n > 2: + value = fibonacci(n-1) + fibonacci(n-2) + + fibonacci_cache[n] = value + return value + + +for n in range(1, 101): + print(n, ":", fibonacci(n)) + diff --git a/algorithms/fibonacci/fibonacci_with_lru_cache.py b/algorithms/fibonacci/fibonacci_with_lru_cache.py new file mode 100755 index 0000000..ff2b331 --- /dev/null +++ b/algorithms/fibonacci/fibonacci_with_lru_cache.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +from functools import lru_cache + +@lru_cache(maxsize = 1000) +def fibonacci(n): + if n == 1: + return 1 + elif n == 2: + return 1 + elif n > 2: + return fibonacci(n-1) + fibonacci(n-2) + + +for n in range(1, 501): + print(n, ":", fibonacci(n))