Skip to content

Add Fibonacci Sequence Recursive Algorithm, Along with a Memoization Example #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion allalgorithms/numeric/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
from .max_numbers import find_max
from .max_numbers import find_max
from .fibonacci import fibonacci, fibonacci_memo
44 changes: 44 additions & 0 deletions allalgorithms/numeric/fibonacci.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# -*- coding: UTF-8 -*-
#
# Numeric Algorithms: Factorials and Memoization
# The All ▲lgorithms library for python
#
# Contributed by: Chance
# Github: @chance-nelson
#


def fibonacci(n):
"""Compute the Fibonacci sequence number at a certain index

This is the obvious recursive approach, and runs on the order of O(n*2).
"""
# Base case 1: fibonacci(1) == 0
if n == 1:
return 0

# Base case 2: fibonacci(2) == 1
elif n == 2:
return 1

return fibonacci(n-1) + fibonacci(n-2)


def memoize(f):
"""Special decorator to add memoization to any recursive function

Keep a cache of results from past runs. This cache can then be referenced
instead of calling the function again.
"""
memory = {}

def inner(num):
if num not in memory:
memory[num] = f(num)

return memory[num]

return inner


fibonacci_memo = memoize(fibonacci)
11 changes: 11 additions & 0 deletions tests/test_numeric.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import unittest

from allalgorithms.numeric import find_max
from allalgorithms.fibonacci import fibonacci, fibonacci_memo


class TestMax(unittest.TestCase):
Expand All @@ -9,5 +10,15 @@ def test_find_max_value(self):
test_list = [3, 1, 8, 7, 4]
self.assertEqual(8, find_max(test_list))


class TestFibonacci(unittest.TestCase):

def test_recursive_fibonacci(self):
self.assertEqual(8, fibonacci(7))

def test_memoize_fibonacci(self):
self.assertEqual(8, fibonacci(7))


if __name__ == "__main__":
unittest.main()