Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # This code, which assumes Python 3.6+, provides a flatten() function and can be
- # tested from the command line with 'python flatten.py'.
- import unittest
- def flatten(arg):
- """
- Flatten an array of arbitrarily nested arrays of integers into a flat array of integers: [[1,2,[3]],4] -> [1,2,3,4].
- Edge case behavior: Invoking on a single integer returns an array containing that integer, flatten(4) -> [4]
- Raise an error if the input contains an unsupported data type (dict, set, tuple, decimal, etc.).
- """
- # If arg is integer, wrap it in an array
- if (type(arg) == type(123)):
- return [arg]
- if type(arg) != type([]):
- raise ValueError(f'Unexpected argument {arg}')
- if not arg:
- return []
- else:
- # Traverse the array depth-first
- return flatten(arg[0]) + flatten(arg[1 : len(arg)])
- class TestFlatten(unittest.TestCase):
- def test_success(self):
- self.assertEqual(flatten([5, 6, 7, 8]), [5, 6, 7, 8])
- self.assertEqual(flatten([[0, 1, 1], [2, [3, 4]], 5]), [0, 1, 1, 2, 3, 4, 5])
- self.assertEqual(flatten([]), [])
- self.assertEqual(flatten(55), [55])
- self.assertEqual(flatten([[[[4]]]]), [4])
- def test_exceptions(self):
- self.assertRaises(ValueError, flatten, [1, 2, 3, 4.5])
- self.assertRaises(ValueError, flatten, {"a": 33})
- self.assertRaises(ValueError, flatten, [1, [2, 3], {"a": [100, 101], "b": 23}, [4, 5]])
- # Run the unit tests
- if __name__ == '__main__':
- unittest.main()
Add Comment
Please, Sign In to add comment