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’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
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
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
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
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
Other Trending Topics
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself.
My main conc...
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
- #elixirconf-us
- #ai
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming











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…