diff --git a/solutions/sum_of_list.py b/solutions/sum_of_list.py new file mode 100644 index 000000000..f99079335 --- /dev/null +++ b/solutions/sum_of_list.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + + +# Write a function that takes a list and returns the sum of that list. + +""" +A module for getting the sum of numbers in a list + +Module contents: + sum_of_list: returns the sum of numbers in a list. + +Created on 02/01/2025 +@author: Ndubuisi Agbo +""" + + +def sum_of_list(numbers: list) -> int | float: + """Gives the sum of the elements in a list. + + Parameters: + numbers (list): the list of numbers to sum. + + Returns: + int or float: the sum of the numbers in the list. + + Raises: + AssertionError: if the list contains a non-numeric element. + AssertionError: if the argument is not a list. + + >>> sum_of_list([3,6,9]) + 18 + + >>> sum_of_list([4.2, 6.9, 7.1]) + 18.2 + + >>> sum_of_list([8, 3.8, 1, 9]) + 21.8 + """ + + assert isinstance(numbers, list), "numbers must be a list" + + # checks that all the elements in the list are a number + for num in numbers: + assert isinstance(num, int | float) + + return sum(numbers) diff --git a/solutions/tests/test_sum_of_list.py b/solutions/tests/test_sum_of_list.py new file mode 100644 index 000000000..c62ea3c7b --- /dev/null +++ b/solutions/tests/test_sum_of_list.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +A module for testing the sum_of_list function. +This module tests the following categories: + - Standard cases + - Edge cases + - Defensive tests + +Created on 02/01/2025 +@author: Ndubuisi Agbo +""" + +import unittest +from ..sum_of_list import sum_of_list + + +class TestSumOfList(unittest.TestCase): + """This module tests the sum_of_list function""" + + # Standard test cases + def test_list_of_integers(self): + """It should return the sum of the list""" + self.assertEqual(sum_of_list([3, 6, 9]), 18) + + def test_list_of_floats(self): + """It should return the sum of the list""" + self.assertEqual(sum_of_list([4.2, 6.9, 7.1]), 18.2) + + def test_list_of_mixed_number(self): + """It should return the sum of the list""" + self.assertEqual(sum_of_list([8, 3.8, 1, 9]), 21.8) + + # Edge cases + def test_empty_list(self): + """Returns zero when an empty list is passed""" + self.assertEqual(sum_of_list([]), 0) + + def test_single_element(self): + """It should return the element in the list""" + self.assertEqual(sum_of_list([7]), 7) + + # Defensive tests + def test_list_of_strings(self): + """Raises AssertionError when a list containing a string is passed""" + with self.assertRaises(AssertionError): + sum_of_list(["3", "9", "6"]) + + def test_non_list(self): + """Raises AssertionError when the argument is not a list""" + with self.assertRaises(AssertionError): + sum_of_list("two") + + +if __name__ == "__main__": + unittest.main()