Skip to content

Instantly share code, notes, and snippets.

@tripy
Created September 24, 2015 21:40
Show Gist options
  • Save tripy/39cdc9e79f20739402f8 to your computer and use it in GitHub Desktop.
Save tripy/39cdc9e79f20739402f8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
def flatten(d_list):
"""Flatten arbitrarily nested arrays of integers/strings.
Raises ValueError if the argument is not a list."""
if not isinstance(d_list, list):
raise ValueError("Argument must be a list type")
# Make a copy to preserve the original
d_list = list(d_list)
i = 0
while i < len(d_list):
# Nothing to do if it is not a list
if not isinstance(d_list[i], list):
i += 1
continue
# Extract the elements from the array and replace the element
d_list[i:i+1] = d_list[i]
return d_list
if __name__ == "__main__":
test_data = [[1, 2, [3]], 4]
print "Original array: %s" % test_data
print "Flattened array: %s" % flatten(test_data)
import pytest
import flatten
def test_flatten_2000_level():
nested = []
# We create a 2000 deep nested list
for elem in xrange(2000):
nested = [nested, elem]
result = flatten.flatten(nested)
expected = range(2000)
assert cmp(result, expected) == 0
def test_flatten_empty():
nested = []
result = flatten.flatten(nested)
expected = []
assert cmp(result, expected) == 0
def test_invalid_type():
data = "bad data"
with pytest.raises(ValueError):
flatten.flatten(data)
@tripy
Copy link
Author

tripy commented Sep 24, 2015

Running the test requires pytest. (pip install pytest && py.test)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment