Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. #!/usr/bin/python3
  2. """
  3. This module provides an example of how to flatten an array of arbitrary
  4. nest integers using recursion.
  5. """
  6. import unittest
  7.  
  8.  
  9. def flatten(array: list) -> list:
  10. """
  11. Accepts an arbitrary list of integers and returns a flattened version
  12. of the list.
  13. >>>flatten([[1, 2, [3]], 4])
  14. [1,2,3,4]
  15.  
  16.  
  17. :param array: arbitrary list of nested integers
  18. :type array: list
  19. :return: flatten list of integers
  20. :rtype: list
  21. :raise: TypeError
  22. """
  23. if type(array) is not list:
  24. raise TypeError
  25.  
  26. flat = []
  27.  
  28. for item in array:
  29.  
  30. if type(item) is int:
  31. flat.append(item)
  32.  
  33. # If the item encountered is a list rather than an integer
  34. # recursively concatenate the list.
  35. elif type(item) is list:
  36. flat = flat + flatten(item)
  37.  
  38. else:
  39. raise TypeError
  40.  
  41. return flat
  42.  
  43.  
  44. class TestFlatten(unittest.TestCase):
  45. def test_flatten(self):
  46. """
  47. Verifies that the flatten() function correctly returns
  48. a flatten list of integers
  49. """
  50. correctly_flatten_list = [1, 2, 3, 4]
  51.  
  52. self.assertListEqual(flatten([[1, 2, [3]], 4]), correctly_flatten_list)
  53. self.assertListEqual(flatten([[1, [2], [3]], 4]), correctly_flatten_list)
  54. self.assertListEqual(flatten([[1, [2], [3]], 4]), correctly_flatten_list)
  55. self.assertListEqual(flatten([[1, [2, [3]]], 4]), correctly_flatten_list)
  56.  
  57. def test_exception_raising(self):
  58. """
  59. Verifies that the flatten() function raises a TypeError when a type
  60. other than int or list is encountered.
  61. """
  62. bad_types = ['r', '3', [1, 2, 'three']]
  63.  
  64. with self.assertRaises(TypeError):
  65.  
  66. for bad_type in bad_types:
  67. flatten(bad_type)
  68.  
  69.  
  70. if __name__ == "__main__":
  71. print("Running tests!")
  72. unittest.main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement