Last active
August 29, 2015 14:06
-
-
Save maliubiao/f51c3660c21bb797f6de to your computer and use it in GitHub Desktop.
flatten.py
This file contains 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
def flatten1(l): | |
s = [(l, 0)] | |
x = [] | |
while s: | |
d, i = s.pop() | |
dlen = len(d) | |
while i < dlen: | |
if isinstance(d[i], list): | |
s.append((d, i+1)) | |
s.append((d[i], 0)) | |
break | |
else: | |
x.append(d[i]) | |
i += 1 | |
return x | |
def flatten2(l): | |
s = [l] | |
x = [] | |
while s: | |
d = s.pop() | |
for i in d: | |
if isinstance(i, list): | |
s.append(i) | |
else: | |
x.append(i) | |
return x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment