From 0636999ac9552576068551a578d4ba94d146ded1 Mon Sep 17 00:00:00 2001 From: Brendan McDevitt Date: Fri, 12 Jan 2018 02:43:57 -0500 Subject: [PATCH] added a last min code change --- ...018-01-01-100-days-of-code-day010.markdown | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/_100-days-of-code/2018-01-01-100-days-of-code-day010.markdown b/_100-days-of-code/2018-01-01-100-days-of-code-day010.markdown index de5f191..1e5608d 100644 --- a/_100-days-of-code/2018-01-01-100-days-of-code-day010.markdown +++ b/_100-days-of-code/2018-01-01-100-days-of-code-day010.markdown @@ -17,3 +17,79 @@ channel with lots of math and science themed videos. That is where I found these tutorials. Here is a [link](https://www.youtube.com/watch?v=Qk0zUZW-U_M&list=PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er-&index=18) to the python video on the fibonacci sequence. +##### No Cache + +```python + +#!/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)) +``` +#### Cache +```python + +#!/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)) +``` +#### Cache using functools lru_cache +```python +#!/usr/bin/env python3 +from functools import lru_cache + +@lru_cache(maxsize = 1000) +def fibonacci(n): + # check if type is positive int + if type(n) != int: + raise TypeError("n must be a positive int") + if n < 1: + raise ValueError("n must be a positive int") + + 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)) +``` +