Skip to content

Instantly share code, notes, and snippets.

@psych0der
Last active July 8, 2018 13:20
Show Gist options
  • Save psych0der/514acbbb1ee3bd413d01314cdaeb07c2 to your computer and use it in GitHub Desktop.
Save psych0der/514acbbb1ee3bd413d01314cdaeb07c2 to your computer and use it in GitHub Desktop.
def listFlattener(arg, *args, **kwargs):
""" Flattens a deeply nested list of integers. But only integers! """
output = list()
# check input type
if type(arg) != list:
raise Exception('Invalid input type. Only accepts list')
def extract_elements(input):
for i in input:
if type(i) == int:
output.append(i)
elif type(i) == list:
# recurs if element is a list
extract_elements(i)
else:
raise Exception(
'Invalid data type encountered : ' + i + ' : ' + str(type(i)))
extract_elements(arg)
return output
if __name__ == "__main__":
# if this program is called directly run some tests
test_input_1 = [[[[1,[2, [[[[90]]]]],3,4,5]]]]
test_output_1 = listFlattener(test_input_1)
if test_output_1 == [1,2,90,3,4,5]:
print('Test-1 passed')
else:
print('Test-1 failed')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment