Created
October 8, 2016 18:54
-
-
Save drathier/cf23d120a1e4afe9a51292dd5eba2d37 to your computer and use it in GitHub Desktop.
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
# Elixir, functional (one understandable, and one fast version) | |
defmodule Flat do | |
# Easy to read, preferred for small input. O(length*depth) | |
def flatten([[a]]), do: flatten([a]) | |
def flatten([a]), do: [a] | |
def flatten([a|bs]), do: flatten(a) ++ flatten(bs) | |
# Linear time, a bit harder to read if you're not used to | |
# high-performant functional programming. O(length+depth) | |
def flatfast(a), do: reverse flatfast(a, []) | |
def flatfast([], r), do: r | |
def flatfast([a|as], r), do: flatfast(as, flatfast(a, r)) | |
def flatfast(a, r), do: [a|r] | |
# Reverse a (linked-)list in linear time. | |
def reverse(a), do: reverse(a, []) | |
def reverse([], b), do: b | |
def reverse([a|as], b), do: reverse as, [a|b] | |
end | |
IO.inspect Flat.flatten([[[[1]],[2]],[3],4]) | |
IO.inspect Flat.flatfast([[[[1]],[2]],[3],4]) | |
# Python, imperative (with a walker) | |
def flatten(a): | |
""" Flatten a list in linear time. """ | |
def walk(a, res): | |
""" | |
Walk walks over the nested lists as if it was a tree, | |
putting all items it finds in `res`. | |
""" | |
if isinstance(a, list): | |
for item in a: | |
walk(item, res) | |
else: | |
res += [a] | |
res = [] | |
walk(a, res) | |
return res | |
print(flatten([[[[1]], [2]], [3], 4])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment