Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- """
- This module provides an example of how to flatten an array of arbitrary
- nest integers using recursion.
- """
- import unittest
- def flatten(array: list) -> list:
- """
- Accepts an arbitrary list of integers and returns a flattened version
- of the list.
- >>>flatten([[1, 2, [3]], 4])
- [1,2,3,4]
- :param array: arbitrary list of nested integers
- :type array: list
- :return: flatten list of integers
- :rtype: list
- :raise: TypeError
- """
- if type(array) is not list:
- raise TypeError
- flat = []
- for item in array:
- if type(item) is int:
- flat.append(item)
- # If the item encountered is a list rather than an integer
- # recursively concatenate the list.
- elif type(item) is list:
- flat = flat + flatten(item)
- else:
- raise TypeError
- return flat
- class TestFlatten(unittest.TestCase):
- def test_flatten(self):
- """
- Verifies that the flatten() function correctly returns
- a flatten list of integers
- """
- correctly_flatten_list = [1, 2, 3, 4]
- self.assertListEqual(flatten([[1, 2, [3]], 4]), correctly_flatten_list)
- self.assertListEqual(flatten([[1, [2], [3]], 4]), correctly_flatten_list)
- self.assertListEqual(flatten([[1, [2], [3]], 4]), correctly_flatten_list)
- self.assertListEqual(flatten([[1, [2, [3]]], 4]), correctly_flatten_list)
- def test_exception_raising(self):
- """
- Verifies that the flatten() function raises a TypeError when a type
- other than int or list is encountered.
- """
- bad_types = ['r', '3', [1, 2, 'three']]
- with self.assertRaises(TypeError):
- for bad_type in bad_types:
- flatten(bad_type)
- if __name__ == "__main__":
- print("Running tests!")
- unittest.main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement