Was it helpful?

Question

Program to find the resolved Unix style path in Python

PythonServer Side ProgrammingProgramming

Suppose we have a Unix path, in a list of strings, we have to find its resolved version. As we know in Unix, ".." denotes the previous directory and "." denotes stay on the current directory. Here resolving indicates evaluation of the two symbols so that we get the final directory we're currently in.

So, if the input is like path = ["usr", "..", "usr", ".", "local", "etc", "foo"], then the output will be ['usr', 'local', 'etc', 'foo'], as the part represents "/usr/../usr/./local/etc" which resolves to "/usr/local/etc/foo"

To solve this, we will follow these steps −

  • s := a new list
  • for each element i in path, do
    • if i is same as '..', then
      • if s is not empty, then
        • delete last element from s
    • otherwise when i is not same as '.', then
      • insert i at the end of s
  • return s

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, path):
      s = []
      for i in path:
         if i == '..':
            if len(s) >0:
               s.pop()
            elif i !='.':
               s.append(i)
      return s
ob = Solution()
print(ob.solve(["usr", "..", "usr", ".", "local", "etc", "foo"]))

Input

["usr", "..", "usr", ".", "local", "etc", "foo"]

Output

['usr', 'local', 'etc', 'foo']
raja
Published on 05-Oct-2020 11:24:16
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top