Skip to content

Instantly share code, notes, and snippets.

@tiholic
Created October 29, 2016 06:00
Show Gist options
  • Save tiholic/f2da2aeec607ac7bfb274ccc5cba1e71 to your computer and use it in GitHub Desktop.
Save tiholic/f2da2aeec607ac7bfb274ccc5cba1e71 to your computer and use it in GitHub Desktop.
Flatten example in python to flatten nested array
#[[1,2,[3]],4] -> [1,2,3,4]
import ast
def flatten(nested_array, flat_array):
for entry in nested_array:
if type(entry) is list:
flatten(entry, flat_array)
else:
flat_array.append(entry)
return flat_array;
def get_input():
nested_input = ast.literal_eval(raw_input("Enter a nested array : "));
if type(nested_input) is list:
return nested_input
else:
print('invalid input\n')
get_input();
print(flatten(get_input(), []))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment