added fibonacci examples and bubblesort example
This commit is contained in:
parent
f71293f7cf
commit
fa30c93bba
4 changed files with 43 additions and 0 deletions
16
algorithms/fibonacci.py
Executable file
16
algorithms/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_with_cache.py
Executable file
27
algorithms/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))
|
||||||
|
|
Loading…
Add table
Reference in a new issue