Skip to content

Instantly share code, notes, and snippets.

@afropolymath
Last active June 28, 2016 22:27
Show Gist options
  • Save afropolymath/07478a629891521d8889e15f44ae8ff2 to your computer and use it in GitHub Desktop.
Save afropolymath/07478a629891521d8889e15f44ae8ff2 to your computer and use it in GitHub Desktop.
Array Flatten
# Simple recursive solution
def flatten(ls):
"""Flatten an array.
Arguments:
ls -- List to flatten
"""
if type(ls) is not list:
raise ValueError("Invalid parameter")
flat = []
for elem in ls:
# Exit function if element is not int or list
if type(elem) not in (int, list):
raise Exception("Cannot parse on or more list elements")
# Continue parsing
if type(elem) == list:
try:
nested = flatten(elem)
flat.extend(nested)
except Exception as e:
raise Exception(str(e))
else:
flat.append(elem)
return flat
# Funny but working solution
def string_flatten(ls):
"""Flatten an array.
Arguments:
ls -- List to flatten
"""
if type(ls) is not list:
raise ValueError("Invalid parameter")
ls_string = str(ls)
mapping = dict.fromkeys(map(ord, '[]'), None)
ls_string = ls_string.translate(mapping)
return ls_string.split(',')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment