95 lines
2.2 KiB
Markdown
95 lines
2.2 KiB
Markdown
---
|
|
layout: post
|
|
title: "day 10"
|
|
date: 2018-01-11
|
|
categories: 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](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))
|
|
```
|
|
|