Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created March 22, 2019 15:36
Show Gist options
  • Save vlad-bezden/e97065bfdf21639869afefda962aaed5 to your computer and use it in GitHub Desktop.
Save vlad-bezden/e97065bfdf21639869afefda962aaed5 to your computer and use it in GitHub Desktop.
Flatten list of lists of etc to one dimensional list
"""
Flatten a List
There is a list which contains integers or other nested lists which may contain yet
more lists and integers which then may contain more lists ...
You should put all of the integer values into one flat list. The order should be as it
was in the original list with string representation from left to right.
Your code should be shorter than 140 characters (with whitespaces).
Input data: A nested list with integers.
Output data: The one-dimensional list with integers.
Example:
flat_list([1, 2, 3]) == [1, 2, 3]
flat_list([1, [2, 2, 2], 4]) == [1, 2, 2, 2, 4]
flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) == [2, 4, 5, 6, 6, 6, 6, 6, 7]
flat_list([-1, [1, [-2], 1], -1]) == [-1, 1, -2, 1, -1]
Precondition: 0 Ôëñ |array| Ôëñ 100
 x  array : -232 < x < 232 or x is a list
depth < 10
Performance results:
f_c took: 0.578635
f_r took: 0.886350
f_m took: 0.392955
f_cl took: 0.221162
"""
import itertools as it
import functools as ft
from timeit import timeit
def f_c(d):
"""using chain."""
return [d] if type(d) is int else [*(it.chain(*[f_c(l) for l in d]))]
def f_r(d):
"""using reduce."""
return [d] if type(d) is int else ft.reduce(lambda p, c: p + f_r(c), d, [])
def f_m(d):
"""using map."""
return [d] if type(d) is int else sum(map(f_m, d), [])
def f_cl(d):
"""using closure."""
r = []
def f(l):
for i in l:
r.append(i) if type(i) is int else f(i)
f(d)
return r
if __name__ == "__main__":
for f in [f_c, f_r, f_m, f_cl]:
assert f([1, 2, 3]) == [1, 2, 3], "First"
assert f([1, [2, 2, 2], 4]) == [1, 2, 2, 2, 4], "Second"
assert f([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) == [
2,
4,
5,
6,
6,
6,
6,
6,
7,
], "Third"
assert f([-1, [1, [-2], 1], -1]) == [-1, 1, -2, 1, -1], "Four"
t = timeit(
stmt="f([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]])",
number=10000,
globals=globals(),
)
print(f"{f.__name__} took: {t:.6f}")
print("Done!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment