brendan.mcdevitt.tech/_100-days-of-code/2018-01-01-100-days-of-code-day010.markdown
2018-01-12 02:43:57 -05:00

2.2 KiB

layout title date categories
post day 10 2018-01-11 programming

100 Days of Code

Day 10:

Made fibonacci programs from tutorials I found on youtube. One that introduces the concept of memoization or storing results of recent function calls to improve the speed of the recursive function. Also a basic bubblesort program in python that I found from another tutorial. This is very basic stuff but I want to make sure I know as much foundational knowledge as I can. Socrataca on youtube is a great channel with lots of math and science themed videos. That is where I found these tutorials. Here is a link to the python video on the fibonacci sequence.

No Cache

#!/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


#!/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

#!/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))