Last active
June 28, 2016 22:27
-
-
Save afropolymath/07478a629891521d8889e15f44ae8ff2 to your computer and use it in GitHub Desktop.
Array Flatten
This file contains hidden or 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
# 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