簡體   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