Created
November 8, 2012 20:44
-
-
Save lssergey/4041457 to your computer and use it in GitHub Desktop.
List flattening
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
# Python does not have tail recursion optimization, | |
# so this function can't handle too deep data structures. | |
# This piece of code was written as a practicing task. | |
def flatten(l): | |
nested = None | |
for i, e in enumerate(l): | |
if isinstance(e, list): | |
nested = e; break | |
if nested is not None: | |
return flatten(l[:i] + nested + l[i+1:]) | |
else: return l | |
def flatten2(l): | |
if not isinstance(l, list): return [l] | |
if not l: return l | |
return flatten(l[0]) + flatten(l[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment