hscspring
I have a python code like this:
class Node:
def __init__(self, path: str):
self.path = path
self.children = {}
class MultiTree:
def __init__(self, root="/"):
self.root = Node(root)
def build(self, lst: list):
for p in lst:
f = p.split("/")
pointer = self.root
for i in range(1, len(f)):
path = "/".join(f[:i+1])
if path not in pointer.children:
node = Node(path)
pointer.children[path] = node
pointer = node
else:
pointer = pointer.children[path]
def dfs(self, root):
stack, res = [], []
stack.append(root)
while len(stack):
curr = stack.pop()
if curr.path not in res:
res.append(curr.path)
stack.extend(reversed(list(curr.children.values())))
return res
That’s a solution to construct a directory tree.
For example, given a dataset like:
list = [“/2/3”, “/2/4”, “/2/4/6”, “/2/3/7”, “/2/3/5”, “/2/3/8”]
the output of dfs will be:
[‘/’, ‘/2’, ‘/2/3’, ‘/2/3/7’, ‘/2/3/5’, ‘/2/3/8’, ‘/2/4’, ‘/2/4/6’]
Now in Elixir, i don’t know how to return the root.
would anyone met the similar situation?
My solution is:
defmodule MultiTree do
defmodule Node do
defstruct path: nil, children: %{}
end
@root "/"
def tree_root(list) do
root = list
|> Enum.reduce(%Node{}, fn p, root ->
f = Enum.drop(String.split(p, "/"), 1)
build(f, f, root)
end)
%Node{ path: @root, children: root }
end
defp build([], full_list, root) do
root
end
defp build([_ | children], full_list, root) do
eol = Enum.count(full_list) - Enum.count(children)
path = "/" <> Enum.join(Enum.slice(full_list, 0..eol-1), "/")
%Node{path: path, children: build(children, full_list, root)}
end
def dfs() do
end
end
However, there’s a problem… The keys are duplicated, for example:
list = ["/2/3", "/2/4", "/2/3/5"]
tree = MultiTree.tree_root(list)
IO.inspect(tree)
The output is:
%MultiTree.Node{
children: %MultiTree.Node{
children: %MultiTree.Node{
children: %MultiTree.Node{
children: %MultiTree.Node{
children: %MultiTree.Node{
children: %MultiTree.Node{
children: %MultiTree.Node{
children: %MultiTree.Node{children: %{}, path: nil},
path: "/2/3"
},
path: "/2"
},
path: "/2/4"
},
path: "/2"
},
path: "/2/3/5"
},
path: "/2/3"
},
path: "/2"
},
path: "/"
}
The expected output should be:
path: "/":
children: {"/2":
{path: "/2",
children: {"/2/3": {path: "/2/3",
children: {"/2/3/4": {path: "/2/3/4", children: {}},
{"/2/3/5}: {path: "/2/3/5", children: {}}
},
},
"/2/4": {path: "/2/4", children: {} }}}}
I also wrote a non-recursion one:
def build_tree(list) do
root = list
|> Enum.reduce(%Node{}, fn p, root ->
f = Enum.drop(String.split(p, "/"), 1)
pointer = root
Enum.reduce(1..Enum.count(f), fn i, _ ->
path = Enum.join(Enum.slice(f, 0..i+1), "/")
ele = Map.get(pointer.children, path)
pointer =
if ele == nil do
node = %Node{ path: path }
Map.put(pointer.children, path, node)
node
else
ele
end
end)
end)
%Node{ path: @root, children: root }
end
however it’s not right…
Trending in Questions
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
Hello,
I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
Hi everyone,
I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding.
I sta...
New
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New
Other Trending Topics
Edit: 2026 May 15 - This post is archived.
Mob is alive!!
Main docs: mob v0.7.11 — Documentation
A bit of explanation for the slightly c...
New
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
Hi everyone!
The first release candidate for the Expert language server project is now available!
We’ve published a press release detai...
New
A little off-topic, but I feel like people here have a good head on their shoulders.
I used to be quite good at making software. Was luc...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #ai
- #elixirconf-us
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #metaprogramming
- #hex










Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
NobbZ
What have you tried in elixir so far?
I have not tried to solve that exercise yet, but from a first glance it should be a matter of splitting and grouping and mearging back…
hscspring
Actually, i have used almost the same code like given above.
Clearly that’s not a good solution (and there is also a bug, i’m trying to fix it).
And i’m now reading several Elixir books and searching the web.
When i’ve finished the code, i’ll post it here~
thanks;)
hscspring
@Nobbz I have updated the code~
hscspring
@ benwilson512
would u please do me a fever?
I have done my best…
mudasobwa
In the first place your expected output is invalid because the node might obviously have several children. One might introduce another struct for children. or have a map
path → childthere. If the latter approach is ok, I’d go withAccessimplementation to ease operations upon this tree afterwards:Of course, the code might be tweaked further to implement
Inspectprotocol for the better representation etc.hscspring
Thanks a lot.
I’m trying .
Qqwy
Here is another approach, using a nested map of maps as tree representation.
I have documented the code to make it hopefully easy to understand.
mudasobwa
hscspring
That’s very clear, thanks very much .
There’s another point: the given list is ordered.
for example, gievn list = [“/2/3”, “/2/4”, “/2/4/6”, “/2/3/7”, “/2/3/5”, “/2/3/8”]
output is [’/’, ‘/2’, ‘/2/3’, ‘/2/3/7’, ‘/2/3/5’, ‘/2/3/8’, ‘/2/4’, ‘/2/4/6’]
“/2/3/7” is ahead of “/2/3/5”.
so, I have to do some sort when building the tree or traveling it.
Actually the task is something below:
Given a list of items, each item with a directory and a create_time, my task is to sort those items by two rules:
Here is a real task example:
The final expected order is
Let me expain
“/folder1”, “/folder2” and “/folder3” are not in the index_dict, so they are sorted by create_time:
“/folder2” > “/folder3” > “/folder1”
then, Let’s loot at the subfolders of folder2
“/folder2/folder2-folder1” and “/folder2/folder2-folder2” are also not in the index_dict (values), so they are sorted by create_time
“/folder2/folder2-folder2” > “/folder2/folder2-folder1”
then, their subdirectories (here are files)
although “/folder2/folder2-folder1/file2” > “/folder2/folder2-folder1/file1” by create_time, in the index_dict, “file1” > “file2”, so the result is ‘/folder2/folder2-folder1/file1’ > ‘/folder2/folder2-folder1/file2’.
Another example, let’s look at folder3, they have sub folders in the index_dict, so sub folders need to be sorted like that
‘/folder3/folder3-folder1’ > ‘/folder3/folder3-folder2’, then ‘/folder3/folder3-folder4’ > ‘/folder3/folder3-folder3’, by their create_time.
My python code is
I have written this task with python in three different ways
However, i can’t do it by Elixir, i am really frustrated though i am new to it…
Maybe i need some more exercise…
If anyone who met this issue before, i feel grateful if you give me some advice.
hscspring
Thanks a lot~
There are several things i didn’t understand, so i have spent some time to learn.
I have tried the code, when i given another different ordered list, like: [“/2/3/8”, “/2/3”, “/2/4”, “/2/4/6”, “/2/3/7”, “/2/3/5”], the result seems a little weird…