Simplify Path in Python

PythonServer Side ProgrammingProgramming

Suppose we have an absolute path for a file (Like Unix File system), we have to simplify it. Or in other words, we have to convert it to the canonical path. In the UNIX-style file system, a period ‘.’ refers to the current directory. And a double period ‘..’ moves the directory up a level (Parent directory). The properties of canonical paths are as follows.

  • Path must always begin with a slash /

  • There must be only a single slash / between two directory names.

  • Last directory name (if it exists) must not end with a trailing /.

  • Canonical path must be the shortest string representing the absolute path.

So for example, if the given paths are “/home/”, “/../” and “/home//user/”, then the converted paths are “/home”, “/”, and “/home/user

Let us see the steps −

  • take a list st, and put ‘/’ into it

  • a := a list of strings after splitting the given path with the delimiter ‘/’

  • for each element i in a

    • if i is double period, then

      • if length of st > 1, then delete last element from st, otherwise continue

    • else if i is single period, then continue

    • else if is not empty string, then insert (‘/’ concatenate i) into st

  • if st has only one element, then return ‘/’

  • return after concatenating all elements present in st

Example

Let us see the following implementation to get better understanding −

class Solution:
   # @param A : string
   @return a strings
   def simplifyPath(self, a):
      st = ['/']
      a = a.split("/")
      for i in a:
         if i == '..':
            if len(st) > 1:
               st.pop()
            else:  
               continue
         elif i == '.':
            continue
         elif i != '':
            st.append("/" + str(i))
      if len(st) == 1:
         return "/"
      return "".join(st[1:])

Input

"/home/"
"/../"
"/home//user/"

Output

"/home"
"/"
"/home/user"
raja
Published on 03-Feb-2020 09:52:47
Advertisements