In some situations, additional information is needed when traversing the tree, depending on the node location. We cannot obtain this information from the node description because the node doesn't contain it. We should collect this information during the crawl. This information may include the full path to the file or the depth of the current node. Any given node won't know where it is. The file location in the file structure depends on the nodes that lead to a particular file.
In this lesson, we'll look at the accumulator, a parameter that collects the necessary data during tree traversal. It may further complicate code, but it's impossible to perform these tasks without it. We will take this task as an example and try to find all empty directories in our file system. First, we will implement a simple version, complicate it, and introduce an accumulator. Here's an example of the file system:
from hexlet import fs
tree = fs.mkdir('/', [
fs.mkdir('etc', [
fs.mkdir('apache'),
fs.mkdir('nginx', [
fs.mkfile('nginx.conf'),
]),
fs.mkdir('consul', [
fs.mkfile('config.json'),
fs.mkdir('data'),
]),
]),
fs.mkdir('logs'),
fs.mkfile('hosts'),
])
There are three empty directories in this structure:
- /logs
- /etc/apache
- /etc/consul/data
The code that does it looks like this:
def find_empty_dir_paths(tree):
name = fs.get_name(tree)
# Getting the children of the node
children = fs.get_children(tree)
# Returning the directory if there are no children
if len(children) == 0:
return name
# Filtering the files because we do not need them