Design File System in Python

PythonServer Side ProgrammingProgramming

Suppose we have to design a file system which provides these two functions −

  1. createPath(path, value) − This creates a new path and associates a value to it if possible and returns True. It returns False if the path already exists or its parent path doesn't exist.
  2. get(path) − This finds the value associated with a path or returns -1 if the path doesn't exist.

The format of a path is one or more concatenated strings of the form − (forward slash) / followed by one or more lowercase English letters. For example, /programming and /programming/problems are valid paths while an empty string and / are not. Here we have to implement these two functions.

So as input, if we create a file-system, then create a path using [‘/a’, 1], then after using get(), with parameter [‘/a’], the output will be 1.

To solve this, we will follow these steps −

  • Define a map d
  • The createPath method will take path and value, this will act like −
  • p := list of components of path split by ‘/’
  • x := d
  • for i in range 1 to length of p – 1
    • if p[i] is not present in x, then return false
    • x := x[p[i]][1]
  • if last element of p is in x, then return false
  • x[last element of p] := a list with v and empty map
  • return true
  • The get() method is taking the path
  • x := d
  • p := list of components of path split by ‘/’
  • for i in range 1 to length of p – 1
    • if p[i] is not present in x, then return -1
    • x := x[p[i]][1]
  • if last element of p is in x, then return x[last element of p][0], otherwise return -1

Example

Let us see the following implementation to get better understanding −

class FileSystem(object):
   def __init__(self):
      self.d = {}
   def create(self, p, v):
      """
      :type path: str
      :type value: int
      :rtype: bool
      """
      p = p.split("/")
      #print(p)
      x = self.d
      for i in range(1,len(p)-1):
         if p[i] not in x:
            return False
         x = x[p[i]][1]
      if p[-1] in x:
         return False
      x[p[-1]] = [v,{}]
      #print(x)
      return True
   def get(self, p):
      """
      :type path: str
      :rtype: int
      """
      x = self.d
      p = p.split("/")
      for i in range(1,len(p)-1):
         if p[i] not in x:
            return -1
         x= x[p[i]][1]
      if p[-1] in x:
         return x[p[-1]][0]
      else:
         return -1

Input

["FileSystem","createPath","get"]
[[],["/a",1],["/a"]]

Output

[null,true,1]
raja
Published on 17-Mar-2020 10:31:32
Advertisements