Solution: Fibonacci#

Write a function that returns a Fibonacci sequence of N elements. Starting from 0, the first 20 terms in the Fibonacci Sequence are:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181

Function definition#

def get_fibonacci(N):

    if (N<=0):
        return None
    elif (N==1):
        return [0]
    elif (N==2):
        return [0,1]

    fibonacci = [0,1,1]
    for i in range(N-3):
        fibonacci.append(fibonacci[-1]+fibonacci[-2])
    
    # return the fibonacci sequence
    return fibonacci

Testing#

Check if your function returns the expected value using the cells below.

import unittest

class UnitTests(unittest.TestCase):
    def test_type(self):
        self.assertEqual(type(get_fibonacci(10)), type([0, 1, 1, 2, 3, 5, 8, 13, 21, 34]), 'The function should return a list')
    def test_size(self):
        self.assertEqual(len(get_fibonacci(500)), 500, 'The function `get_fibonacci(500)` should return a list with len=500')
    def test_odd(self):
        self.assertEqual(get_fibonacci(9), [0, 1, 1, 2, 3, 5, 8, 13, 21])
    def test_even(self):
        self.assertEqual(get_fibonacci(18), [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597])
    def test_zero(self):
        self.assertEqual(get_fibonacci(0), None, '`get_fibonacci(0)` should return `None`')
    def test_one(self):
        self.assertEqual(get_fibonacci(1), [0], '`get_fibonacci(1)` should return `[0]`')
    def test_two(self):
        self.assertEqual(get_fibonacci(2), [0,1], '`get_fibonacci(2)` should return `[0,1]`')

unittest.main(argv=[''], verbosity=2,exit=False)
test_even (__main__.UnitTests) ... 
ok
test_odd (__main__.UnitTests) ... 
ok
test_one (__main__.UnitTests) ... 
ok
test_size (__main__.UnitTests) ... 
ok
test_two (__main__.UnitTests) ... 
ok
test_type (__main__.UnitTests) ... 
ok
test_zero (__main__.UnitTests) ... 
ok

----------------------------------------------------------------------
Ran 7 tests in 0.004s

OK
<unittest.main.TestProgram at 0x7f9bd0a69f90>