|
12 | 12 | 8. Fibonacci.fib()
|
13 | 13 | 9. Fibonacci.fast_fib()
|
14 | 14 |
|
| 15 | +## Code Examples |
| 16 | +One interesting implementation is this algorithm to compute fibonacci sequences, it runs in O(1) time provided that the cache contains the previous two sequences. Generating the previous sequences is usually done using loops. |
| 17 | +```python3 |
| 18 | + @staticmethod |
| 19 | + def fast_fib(n: int, cache: {int: int}) -> int: |
| 20 | + """Fibonacci sequence algorithm utilizing dynamic programing and memoization""" |
| 21 | + if n == 0: |
| 22 | + cache[n] = 0 |
| 23 | + return 0 |
| 24 | + |
| 25 | + if n == 1: |
| 26 | + cache[n] = 1 |
| 27 | + return 1 |
| 28 | + |
| 29 | + cache[n] = cache[n - 2] + cache[n - 1] |
| 30 | + return cache[n] |
| 31 | +``` |
| 32 | + |
15 | 33 | ## Java Implementation
|
16 | 34 | These were originally implemented in Java. You can find the source [here](https://github.com/dev-xero/java-algorithms-exercise-practice)
|
0 commit comments