I would like to get some code review for my recursive implementation of python flatten array method.
Write a piece of functioning code that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
I'm particularly looking for some feedback on the following:
Is usage of TypeError exception justified? Did I miss some valid edge cases in my tests? Here is my solution including unit tests:
def flatten(input_array):
result_array = []
for element in input_array:
if isinstance(element, int):
result_array.append(element)
elif isinstance(element, list):
result_array += flatten(element)
return result_array
it has passed all of the following tests
from io import StringIO
import sys
# custom assert function to handle tests
# input: count {List} - keeps track out how many tests pass and how many total
# in the form of a two item array i.e., [0, 0]
# input: name {String} - describes the test
# input: test {Function} - performs a set of operations and returns a boolean
# indicating if test passed
# output: {None}
def expect(count, name, test):
if (count is None or not isinstance(count, list) or len(count) != 2):
count = [0, 0]
else:
count[1] += 1
result = 'false'
error_msg = None
try:
if test():
result = ' true'
count[0] += 1
except Exception as err:
error_msg = str(err)
print(' ' + (str(count[1]) + ') ') + result + ' : ' + name)
if error_msg is not None:
print(' ' + error_msg + '\n')
# code for capturing print output
#
# directions: capture_print function returns a list of all elements that were
# printed using print with the function that it is given. Note that
# the function given to capture_print must be fed using lambda.
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._stringio = StringIO()
return self
def __exit__(self, *args):
self.extend(self._stringio.getvalue().splitlines())
sys.stdout = self._stdout
def capture_print(to_run):
with Capturing() as output:
pass
with Capturing(output) as output: # note the constructor argument
to_run()
return output
def test():
results = flatten([1, [2, 3, [4]], 5, [[6]]])
return (len(results) == 6 and
results[0] == 1 and
results[1] == 2 and
results[2] == 3 and
results[3] == 4 and
results[4] == 5 and
results[5] == 6)
expect(test_count, 'should return [1,2,3,4,5,6] output for [1, [2, 3, [4]], 5, [[6]]] input', test)
def test():
results = flatten([])
return len(results) == 0
expect(test_count, 'should return [] output for [] input', test)
def test():
results = flatten([1, [2, 3, [4], []], [], 5, [[], [6]]])
return (len(results) == 6 and
results[0] == 1 and
results[1] == 2 and
results[2] == 3 and
results[3] == 4 and
results[4] == 5 and
results[5] == 6)
expect(test_count, 'should return [1,2,3,4,5,6] output for [1, [2, 3, [4], []], [], 5, [[], [6]]] input (note the empty arrays)', test)
print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')
TypeError
in your code, neither in your tests... Can you explain what you had in mind? \$\endgroup\$