I submitted a solution to problem 588: Design In-Memory File System. My solution passes more than 40 tests, but at some point it fails because for some reason Leetcode represents the value I am returning differently. Basically, my solution returns a string say "ABC", but the correction system takes it as ["A", "B", "C"] and marks me wrong. I verified that I am returning a string by printing on stdout. I am including my code below, in addition to the problematic test case. I really appreciate it If someone can try it out and help with this.
My code is:
class File:
def __init__(self, n : str, cont = None):
self.content = cont
self.name = n
def getName(self):
return self.name
class Folder:
def __init__(self, n : str):
self.name = n
self.cont = {}
class FileSystem:
def __init__(self):
self.root = Folder('/')
def getpwd(self, path):
if path == '/':
return self.root
folders = path.split('/')
pwd = self.root
for dr in folders:
if dr == "":
continue
print(f'Going into {dr}')
pwd = pwd.cont[dr]
print(pwd.name)
return pwd
def ls(self, path: str) -> List[str]:
pwd = self.getpwd(path)
# Check if this a file or a folder
if type(pwd) == type(Folder('')):
return sorted([k for k in pwd.cont.keys()])
else:
return pwd.name
def mkdir(self, path: str) -> None:
folders = path.split('/')
pwd = self.root
for dr in folders:
if dr == "":
continue
# check if directory exists
# if it does change pwd to it
# else create it first then change directory
if dr in pwd.cont:
pwd = pwd.cont[dr]
else:
#print(f'Folder {dr} is created in {pwd.name}')
pwd.cont[dr] = Folder(dr)
pwd = pwd.cont[dr]
def addContentToFile(self, filePath: str, content: str) -> None:
#print(f'Adding content to {filePath}')
folders = filePath.split('/')
pwd = self.root
# last name is for file
for dr in folders[:-1]:
if dr == "":
continue
# check if directory exists
# if it does change pwd to it
# else create it first then change directory
if dr in pwd.cont:
pwd = pwd.cont[dr]
else:
#print(f'Folder {dr} is created in {pwd.name}')
pwd.cont[dr] = Folder(dr)
pwd = pwd.cont[dr]
#print(f'PWD is {pwd.name}')
filename = folders[-1]
#print(f'file name is {filename}')
if filename not in pwd.cont:
pwd.cont[filename] = File(filename, content)
else:
pwd.cont[filename].content += content
#print('File created successfully')
def readContentFromFile(self, filePath: str) -> str:
folders = filePath.split('/')
pwd = self.root
# last name is for file
for dr in folders[:-1]:
if dr == "":
continue
pwd = pwd.cont[dr]
filename = folders[-1]
return pwd.cont[filename].content
And here is the test case it fails (the difference is highlighted):
Input: ["FileSystem","mkdir","ls","mkdir","ls","ls","ls","addContentToFile","ls","ls","ls"]
[[],["/m"],["/m"],["/w"],["/"],["/w"],["/"],["/dycete","emer"],["/w"],["/"],["/dycete"]]
Output: [null,null,[],null,["m","w"],[],["m","w"],null,[],["dycete","m","w"],["d","y","c","e","t","e"]]
Expected: [null,null,[],null,["m","w"],[],["m","w"],null,[],["dycete","m","w"],["dycete"]]