added a last min code change
This commit is contained in:
parent
267b86680c
commit
0636999ac9
1 changed files with 76 additions and 0 deletions
|
@ -17,3 +17,79 @@ channel with lots of math and science themed videos. That is where I found
|
||||||
these tutorials. Here is a
|
these tutorials. Here is a
|
||||||
[link](https://www.youtube.com/watch?v=Qk0zUZW-U_M&list=PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er-&index=18)
|
[link](https://www.youtube.com/watch?v=Qk0zUZW-U_M&list=PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er-&index=18)
|
||||||
to the python video on the fibonacci sequence.
|
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))
|
||||||
|
```
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue