added one more fibonacci example using the lru_cache from functools standard lib
This commit is contained in:
parent
fa30c93bba
commit
398c60feb5
3 changed files with 58 additions and 0 deletions
16
algorithms/fibonacci/fibonacci.py
Executable file
16
algorithms/fibonacci/fibonacci.py
Executable file
|
@ -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))
|
27
algorithms/fibonacci/fibonacci_with_cache.py
Executable file
27
algorithms/fibonacci/fibonacci_with_cache.py
Executable file
|
@ -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))
|
||||
|
15
algorithms/fibonacci/fibonacci_with_lru_cache.py
Executable file
15
algorithms/fibonacci/fibonacci_with_lru_cache.py
Executable file
|
@ -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))
|
Loading…
Add table
Reference in a new issue