繁体   English   中英

设计内存文件系统 - Python - Trie - Leetcode 错误

[英]Design In-Memory File System - Python - Trie - Leetcode Error

我正在尝试解决以下 leetcode 问题

设计一个模拟内存文件系统的数据结构。

实现 FileSystem 类:

FileSystem() 初始化系统对象。 List ls(String path) 如果 path 是文件路径,则返回一个仅包含该文件名的列表。 如果 path 是目录路径,则返回此目录中的文件和目录名称列表。 答案应按字典顺序排列。 void mkdir(String path) 根据给定的路径创建一个新目录。 给定的目录路径不存在。 如果路径中的中间目录不存在,您也应该创建它们。 void addContentToFile(String filePath, String content) 如果 filePath 不存在,则创建包含给定内容的文件。 如果 filePath 已存在,则将给定内容附加到原始内容。 String readContentFromFile(String filePath) 返回文件中位于 filePath 的内容。

示例 1:

输入

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

输出

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

解释

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"

下面是我为它编写的代码

class FileSystem:

def __init__(self):
    self.root = {}

def ls(self, path: str) -> List[str]:
    path = path.split('/')
    node = self.root
    for 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.root
    for char in path:
        if char not in node:
            node[char] = {}
        node = node[char]
        
 

def addContentToFile(self, filePath: str, content: str) -> None:
    node = self.root
    filePath = 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.root
    filePath = 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)


        
            

这是我正在努力的输入

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

这是预期的输出:

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

这是我不正确的输出

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

我相信当我无法为 ls 语句返回文件名而是返回语句的内容时,问题就出现了

如何确保在运行 ls 方法时返回路径中的文件名或内容而不是文件内容?

干杯!

在数据结构中对文件进行编码的方式使得很难将其与同名目录区分开来。 此外,您可以将文件的内容定义为“文件”的子目录。 如果您不将文件定义为字典,而是将其定义为自己的类型(如File类的实例),则使用起来会更容易。 这样就可以很容易地识别它,并且它的内容可以是一个属性。

这里的代码更新了编码文件的想法。

同时,我也:

  • dict的子类FileSystem ,因此它不需要root属性。

  • 定义了一个单独的方法来沿着路径走——因为这是几乎所有其他方法都必须做的事情,所以我们避免了代码重复。 此方法的额外参数将确定是否应自动创建丢失的目录,还是应引发错误,以及路径应指向的位置(文件、目录或两者之一)

  • 定义了一个具有名称和内容的类File

class File:
    def __init__(self, name, content=""):
        self.name = name
        self.content = content
        
class 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 = self
        directories = path.split("/") if path else []
        path = ""
        for i, directory in enumerate(directories):
            path += "/" + directory
            parent = child
            if not directory in parent:
                if not autocreate:
                    raise ValueError(f"Invalid path: '{path}'")
                # auto create entry
                parent[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 child
        
    def 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 += content
            
    def readContentFromFile(self, filePath: str) -> str:
        return self.walk(filePath, False, "file").content

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM