Design In-Memory File System - Python - Trie - Leetcode Error

2024/7/7 7:40:18

I am trying to solve the below leetcode problem

Design a data structure that simulates an in-memory file system.

Implement the FileSystem class:

FileSystem() Initializes the object of the system. List ls(String path) If path is a file path, returns a list that only contains this file's name. If path is a directory path, returns the list of file and directory names in this directory. The answer should in lexicographic order. void mkdir(String path) Makes a new directory according to the given path. The given directory path does not exist. If the middle directories in the path do not exist, you should create them as well. void addContentToFile(String filePath, String content) If filePath does not exist, creates that file containing given content. If filePath already exists, appends the given content to original content. String readContentFromFile(String filePath) Returns the content in the file at filePath.

Example 1:

Input

["FileSystem", "ls", "mkdir", "addContentToFile", "ls", "readContentFromFile"]
[[], ["/"], ["/a/b/c"], ["/a/b/c/d", "hello"], ["/"], ["/a/b/c/d"]]

Output

[null, [], null, null, ["a"], "hello"]

Explanation

FileSystem fileSystem = new FileSystem();
fileSystem.ls("/");                         // return []
fileSystem.mkdir("/a/b/c");
fileSystem.addContentToFile("/a/b/c/d", "hello");
fileSystem.ls("/");                         // return ["a"]
fileSystem.readContentFromFile("/a/b/c/d"); // return "hello"

Below is the code I have written for it

class FileSystem:def __init__(self):self.root = {}def ls(self, path: str) -> List[str]:path = path.split('/')node = self.rootfor char in path:if char in node:node = node[char]print(node)node = list(node)print(node)print(path)return sorted(node)def mkdir(self, path: str) -> None:path = path.split('/')node = self.rootfor char in path:if char not in node:node[char] = {}node = node[char]def addContentToFile(self, filePath: str, content: str) -> None:node = self.rootfilePath = filePath.split('/')for char in filePath:if char not in node:node[char] = {}node = node[char]node[content] = '*'def readContentFromFile(self, filePath: str) -> str:node = self.rootfilePath = filePath.split('/')for char in filePath:if char not in node:return "Error"node = node[char]result_list = list(node.keys())return "".join(result_list)

Here is an input I am struggling with

["FileSystem","mkdir","ls","ls","mkdir","ls","ls","addContentToFile","ls","ls","ls"]
[[],["/goowmfn"],["/goowmfn"],["/"],["/z"],["/"],["/"],["/goowmfn/c","shetopcy"],["/z"],["/goowmfn/c"],["/goowmfn"]]

Here is the expected output:

[null,null,[],["goowmfn"],null,["goowmfn","z"],["goowmfn","z"],null,[],["c"],["c"]]

Here is my incorrect output

[null,null,[],["goowmfn"],null,["goowmfn","z"],["goowmfn","z"],null,[],["shetopcy"],["c"]]

I believe the issue comes in when I am not able to return the name of the file for a ls statement but instead return the content of the statement

How do I ensure that when the ls method is run I return the file name or contents in the path not the file contents?

Cheers!

Answer

The way you encode a file in the data structure makes it hard to distinguish it from a directory with the same name. Moreover, you define the content of the file as if it were a subdirectory of the "file". It will be easier to work with, if you define the file not as a dictionary, but as its own type (like the instance of a File class). That way it can be easily recognised and its content can be an attribute.

Here the code updated with that idea on encoding a file.

At the same time, I also:

  • Subclassed FileSystem from dict, so it does not need a root attribute.

  • Defined a separate method for walking down a path -- since that is what almost every other method must do, and so we avoid code repetition. Extra arguments to this method will determine whether missing directories should be created automatically, or an error should be thrown, and what the path is supposed to point at (a file, a directory, or either)

  • Defined a class File with name and content.

class File:def __init__(self, name, content=""):self.name = nameself.content = contentclass FileSystem(dict):def walk(self, path: str, autocreate: bool=False, expected: str="any") -> Union['FileSystem', File]:if not path.startswith("/"):raise ValueError("Path should start with slash")path = path[1:]if path.endswith("/"):path = path[:-1]child = selfdirectories = path.split("/") if path else []path = ""for i, directory in enumerate(directories):path += "/" + directoryparent = childif not directory in parent:if not autocreate:raise ValueError(f"Invalid path: '{path}'")# auto create entryparent[directory] = File(directory) if i == len(directories) - 1 and expected == "file" else FileSystem()child = parent[directory]if expected != "any" and (expected == "file") != isinstance(child, File):raise ValueError(f"'{path}' is not a {expected}")return childdef ls(self, path: str) -> List[str]:node = self.walk(path)return sorted(node) if isinstance(node, FileSystem) else [node.name]def mkdir(self, path: str) -> None:self.walk(path, True, "directory")def addContentToFile(self, filePath: str, content: str) -> None:self.walk(filePath, True, "file").content += contentdef readContentFromFile(self, filePath: str) -> str:return self.walk(filePath, False, "file").content
https://en.xdnf.cn/q/120145.html

Related Q&A

OpenTurns Error when trying to use kernel build [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

How to write data to excel with header using Pandas?

I want to write the excel file with the header isI have data and I want to fill out the excel file. Then the expected result isThis is my code but it does not show as my expected. Could you help me to …

Cooldown format in days discord.py

Im currently making a command which has a cooldown of 5 days, and Im currently using this code for the cooldown. def better_time(self, cd:int):time = f"{cd}s"if cd > 60:minutes = cd - (cd …

From scraper_user.items import UserItem ImportError: No module named scraper_user.items

I am following this guide for scraping data from instagram: http://www.spataru.at/scraping-instagram-scrapy/ but I get this error:mona@pascal:~/computer_vision/instagram/instagram$ ls instagram scrap…

Correct way of coding a Guess the Number game in Python [closed]

Closed. This question is off-topic. It is not currently accepting answers.Want to improve this question? Update the question so its on-topic for Stack Overflow.Closed 11 years ago.Improve this questio…

How do i stop the infinite loop for the if and elif part?

c = random.randint(0,5) guess =int(input("=")) while True:if guess > c:print("you failed the test")elif guess <c: print("you messed up")else:print("you are the …

How to zip a list of lists

I have a list of listssample = [[A,T,N,N],[T, C, C, C]],[[A,T,T,N],[T, T, C, C]].I am trying to zip the file such that only A/T/G/C are in lists and the output needs to be a list[[AT,TCCC],[ATT,TTCC]]W…

I want to make a Guess the number code without input

import random number = random.randint(1, 10)player_name = "doo" number_of_guesses = 0 print(I\m glad to meet you! {} \nLet\s play a game with you, I will think a number between 1 and 10 then …

How to zip keys within a list of dicts

I have this object: dvalues = [{column: Environment, parse_type: iter, values: [AirportEnclosed, Bus, MotorwayServiceStation]}, {column: Frame Type, parse_type: list, values: [All]}]I want a zipped out…

AttributeError: DataFrame object has no attribute allah1__27

Im trying to solve this and Im pretty sure the code is right but it keeps getting me the same Error.I have tried this:import datetime from datetime import datetime as datettest_df = shapefile.copy() te…