Last active
March 17, 2017 16:49
-
-
Save silveira/1229108 to your computer and use it in GitHub Desktop.
Examples of non-recursive function to flatten and sort a list. Keeping sorting by the way is greatly better because of timsort on Python.
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
#!/usr/bin/python | |
""" | |
Flatten a list | |
""" | |
def flatten(notflat): | |
flat = [] | |
while notflat: | |
element = notflat.pop() | |
if isinstance(element, list): | |
notflat.extend(element) | |
else: | |
flat.append(element) | |
return flat.reverse() | |
if __name__ == "__main__" : | |
test = [1,2,[3,4],[5,6], [7], 8, [[[[1]]]], 2,3,[1,[2,[3],5],[7,[8],9]], [1,[2],[1,2,3,4]]] | |
print flatten(test) | |
# [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 1, 2, 3, 5, 7, 8, 9, 1, 2, 1, 2, 3, 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment