Skip to content

Instantly share code, notes, and snippets.

@towkir
Last active October 28, 2016 07:52
Show Gist options
  • Save towkir/7fc552dc22d70c126fd05a23c871c859 to your computer and use it in GitHub Desktop.
Save towkir/7fc552dc22d70c126fd05a23c871c859 to your computer and use it in GitHub Desktop.
This script takes a nested array of integer numbers and returns a flat array
print("This program takes a nested array of integer numbers and returns a flat array")
print("Press Ctrl+C to exit")
try:
while True:
flat_array = []
nested_array = input("Pleas input your arbitrary array:\n")
def loop_through_list(given_list): # this function checks if list items are a list themselves
for a in given_list: # and if so, it calls itself within that list item.
if type(a) == list:
loop_through_list(a)
else:
flat_array.append(a) # otherwise, appends the integer list item into the flat array
try:
list(nested_array)
except (NameError, TypeError, ValueError): # trying to catch exception errors
print("Please input Arrays only")
except SyntaxError:
print("Make sure your array is nested properly with correct syntax")
else:
for items in nested_array:
if type(items) == str:
print("Make sure array contains numbers only")
break # the loop breaks if it finds a single non integer (string) item
elif type(items) == int:
flat_array.append(items)
elif type(items) == list: # running loops inside loop to fetch the lists inside list
loop_through_list(items)
if len(flat_array) > 0: # now the flat array will be printed only if it's not empty
print flat_array
except KeyboardInterrupt:
print("You have exited")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment