Created
September 22, 2016 23:47
-
-
Save chrisamow/3db5102ca5f1fb074d605754625da964 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def flatten(intlist): | |
"""flatten an arbitrarily nested list of integers | |
e.g. | |
flatten([[1,2,[3]],4]) returns [1,2,3,4] | |
""" | |
retlist = [ ] | |
for n in intlist: | |
if type(n) == list: | |
retlist.extend(flatten(n)) | |
else: | |
retlist.append(n) | |
return retlist | |
if __name__ == '__main__': | |
#forgoing external unit test to keep this all in one file | |
#using a list as a key in a dictionary not possible | |
tests = { | |
"[ ]" : [ ], | |
"[1,2,3,4]" : [1,2,3,4], | |
"[0,0,0,0]" : [0,0,0,0], | |
"[[1,2,[3]],4]" : [1,2,3,4], | |
"[1, 3, [4, 6, 7], 9, 0]" : [1,3,4,6,7,9,0] | |
} | |
for k,v in tests.iteritems(): | |
test = eval(k) | |
result = 'passed' if flatten(test) == v else 'failed' | |
print('test {0} {1}, => {2}'.format(result, k, v)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment