diff options
author | William Carroll <wpcarro@gmail.com> | 2020-01-15T14·25+0000 |
---|---|---|
committer | William Carroll <wpcarro@gmail.com> | 2020-01-15T14·25+0000 |
commit | d4d8397e5ffe6734ed5861e48ce475848956a3fe (patch) | |
tree | 7f0f8563750a2084ad9a4b9908cbb5316fe6bf10 /data_structures_and_algorithms/nth-fibonacci.py | |
parent | b4ee283b23b8a85c75339e07b0adf43d1c3ca770 (diff) |
Add InterviewCake.com examples
Adds some of the code I generated while studying for a role transfer at Google using the fantastic resource, InterviewCake.com. This work predates the mono-repo. I should think of ways to DRY up this code and the code in crack_the_coding_interview, but I'm afraid I'm creating unnecessary work for myself that way.
Diffstat (limited to 'data_structures_and_algorithms/nth-fibonacci.py')
-rw-r--r-- | data_structures_and_algorithms/nth-fibonacci.py | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/data_structures_and_algorithms/nth-fibonacci.py b/data_structures_and_algorithms/nth-fibonacci.py new file mode 100644 index 000000000000..cdb2846ea338 --- /dev/null +++ b/data_structures_and_algorithms/nth-fibonacci.py @@ -0,0 +1,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) |