Guest User

Untitled

a guest
Nov 13th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. # This code, which assumes Python 3.6+, provides a flatten() function and can be
  2. # tested from the command line with 'python flatten.py'.
  3.  
  4. import unittest
  5.  
  6. def flatten(arg):
  7. """
  8. Flatten an array of arbitrarily nested arrays of integers into a flat array of integers: [[1,2,[3]],4] -> [1,2,3,4].
  9. Edge case behavior: Invoking on a single integer returns an array containing that integer, flatten(4) -> [4]
  10. Raise an error if the input contains an unsupported data type (dict, set, tuple, decimal, etc.).
  11. """
  12. # If arg is integer, wrap it in an array
  13. if (type(arg) == type(123)):
  14. return [arg]
  15. if type(arg) != type([]):
  16. raise ValueError(f'Unexpected argument {arg}')
  17. if not arg:
  18. return []
  19. else:
  20. # Traverse the array depth-first
  21. return flatten(arg[0]) + flatten(arg[1 : len(arg)])
  22.  
  23. class TestFlatten(unittest.TestCase):
  24. def test_success(self):
  25. self.assertEqual(flatten([5, 6, 7, 8]), [5, 6, 7, 8])
  26. self.assertEqual(flatten([[0, 1, 1], [2, [3, 4]], 5]), [0, 1, 1, 2, 3, 4, 5])
  27. self.assertEqual(flatten([]), [])
  28. self.assertEqual(flatten(55), [55])
  29. self.assertEqual(flatten([[[[4]]]]), [4])
  30.  
  31. def test_exceptions(self):
  32. self.assertRaises(ValueError, flatten, [1, 2, 3, 4.5])
  33. self.assertRaises(ValueError, flatten, {"a": 33})
  34. self.assertRaises(ValueError, flatten, [1, [2, 3], {"a": [100, 101], "b": 23}, [4, 5]])
  35.  
  36. # Run the unit tests
  37. if __name__ == '__main__':
  38. unittest.main()
Add Comment
Please, Sign In to add comment