Can you demonstrate how to write functions for creating and managing a file tree, including adding directories, inserting files, navigating the structure, and deleting elements?
Crack Every Online Interview
Get Real-Time AI Support, Zero Detection
This site is powered by
OfferInAI.com Featured Answer
Question Analysis
The question requires you to design and implement a system for managing a file tree structure programmatically. The tasks involved include:
- Creating a file tree: This involves initializing the root of the file tree.
- Adding directories: You need to implement functionality to add new directories to the file tree.
- Inserting files: This involves adding files to specific directories within the file tree.
- Navigating the structure: Implement ways to traverse or navigate through the file tree, possibly listing contents.
- Deleting elements: Provide functionality to remove files or directories.
This question tests your understanding of data structures (specifically trees) and your ability to manipulate such structures programmatically. It also assesses your skills in code organization and modular design.
Answer
Below is a Python implementation to demonstrate creating and managing a file tree with the specified functionalities:
class Node:
def __init__(self, name, is_file=False):
self.name = name
self.is_file = is_file
self.children = {}
class FileTree:
def __init__(self):
self.root = Node("root")
def add_directory(self, path):
current = self.root
for part in path.strip("/").split("/"):
if part not in current.children:
current.children[part] = Node(part)
current = current.children[part]
def insert_file(self, path, file_name):
current = self.root
for part in path.strip("/").split("/"):
if part in current.children:
current = current.children[part]
else:
raise ValueError(f"Directory {part} does not exist")
if file_name not in current.children:
current.children[file_name] = Node(file_name, is_file=True)
def navigate(self, path):
current = self.root
for part in path.strip("/").split("/"):
if part in current.children:
current = current.children[part]
else:
raise ValueError(f"Path {path} does not exist")
return current
def delete(self, path, name):
parent = self.navigate(path)
if name in parent.children:
del parent.children[name]
else:
raise ValueError(f"Element {name} does not exist in {path}")
def list_contents(self, path):
node = self.navigate(path)
return list(node.children.keys())
# Example Usage
file_tree = FileTree()
file_tree.add_directory("/home/user/docs")
file_tree.insert_file("/home/user/docs", "file1.txt")
file_tree.insert_file("/home/user/docs", "file2.txt")
print(file_tree.list_contents("/home/user/docs")) # ['file1.txt', 'file2.txt']
file_tree.delete("/home/user/docs", "file1.txt")
print(file_tree.list_contents("/home/user/docs")) # ['file2.txt']
Key Points:
- Tree Structure: The
Node
class represents both files and directories. Directories can have children, whereas files cannot. - Path Management: Paths are used to navigate through the tree, and the functions handle the creation, insertion, and deletion based on path strings.
- Error Handling: The implementation includes basic error handling to manage cases of non-existent paths.
This solution is structured to be simple and extendable. You can add more features like searching or moving files and directories as needed.