Answer the question
In order to leave comments, you need to log in
How to make a directory tree from an array of paths?
There is an array of type string mas = [
E:/folder/maps
E:/1/2/3
E:/folder/new
E:/folder/maps/2
D:/papka/echepapka
E:/1/path/dir
]
What algorithm to bypass this array to get the hierarchy of all folders?
Preferably in python
Answer the question
In order to leave comments, you need to log in
For example, you can add to a dictionary:
from functools import reduce
from pathlib import PurePosixPath
paths = [
'E:/folder/maps',
'E:/1/2/3',
'E:/folder/new',
'E:/folder/maps/2',
'D:/papka/echepapka',
'E:/1/path/dir',
]
tree = {}
for path in map(PurePosixPath, paths):
reduce(lambda node, part: node.setdefault(part, {}), path.parts, tree)
{'E:': {'folder': {'maps': {'2': {}}, 'new': {}},
'1': {'2': {'3': {}}, 'path': {'dir': {}}}},
'D:': {'papka': {'echepapka': {}}}}
Yes, it seems that a cunning algorithm is not needed here. Take the next line, break it into separate tokens.
Further in the token loop, you try to find a partial path, and if it doesn’t work, add it to the tree.
For example, you added the first 2 paths:
E
|-1
| |-2
| |-3
|-folder
|-maps
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question