about summary refs log tree commit diff
path: root/scratch/deepmind/part_two/nth-fibonacci.py
blob: 14e176b62aabd1240894cabf1e7afe5a14643c7e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import unittest


# Compute the fibonacci using a bottom-up algorithm.
def fib(n):
    if n < 0:
        raise Error('Cannot call fibonacci with negative values')
    cache = [0, 1]
    for i in range(n):
        cache[0], cache[1] = cache[1], cache[0] + cache[1]
    return cache[0]


# Compute the fibonacci using memoization.
def fib_memoized(n):
    cache = {
        0: 0,
        1: 1,
    }

    def do_fib(n):
        if n < 0:
            raise Error('The fib function does not support negative inputs')

        if n in cache:
            return cache[n]

        cache[n - 1] = do_fib(n - 1)
        cache[n - 2] = do_fib(n - 2)
        return cache[n - 1] + cache[n - 2]

    return do_fib(n)


# Tests
class Test(unittest.TestCase):
    def test_zeroth_fibonacci(self):
        actual = fib(0)
        expected = 0
        self.assertEqual(actual, expected)

    def test_first_fibonacci(self):
        actual = fib(1)
        expected = 1
        self.assertEqual(actual, expected)

    def test_second_fibonacci(self):
        actual = fib(2)
        expected = 1
        self.assertEqual(actual, expected)

    def test_third_fibonacci(self):
        actual = fib(3)
        expected = 2
        self.assertEqual(actual, expected)

    def test_fifth_fibonacci(self):
        actual = fib(5)
        expected = 5
        self.assertEqual(actual, expected)

    def test_tenth_fibonacci(self):
        actual = fib(10)
        expected = 55
        self.assertEqual(actual, expected)

    def test_negative_fibonacci(self):
        with self.assertRaises(Exception):
            fib(-1)


unittest.main(verbosity=2)