about summary refs log tree commit diff
path: root/universe/data_structures_and_algorithms/nth-fibonacci.py
blob: cdb2846ea3388c2edf773d57a680fa8ab9b26f58 (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
import unittest


################################################################################
# Solution
################################################################################
def fib(n):
    """This should be accomplishable in O(1) space."""
    if n in {0, 1}:
        return n
    a = 0  # i = 0
    b = 1  # i = 1
    for x in range(2, n + 1):
        result = a + b
        a = b
        b = result
    return result


################################################################################
# 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)