0

I have been given a list of folder structures like

path  = [ "/home/User/Desktop/gfg/test",
"/home/User/Desktop/gfg/file",
"/home/User/Desktop/geeks/folders" ,
"/home/User/Desktop/../geeks/a/folders"]

and we have to find out the common subdirectory among all the file paths. For example output of the above path list should be "home/User".

Solution:

Approach1: Iterate through each folder path and get the matrix of words and then compare each column one by one. Wherever the column condition fails return the most recent string till that column.

Happy to see more solutions and approach to solve this question. Feel free to answer.

Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
  • 4
    You could use [os.path.commonpath](https://docs.python.org/3/library/os.path.html#os.path.commonpath), just have to make all paths absolute - `os.path.commonpath(map(os.path.abspath, path))` – Iain Shelvington Sep 24 '22 at 22:59

1 Answers1

0
### Considering the   
##    path = [ "/home/User/Desktop/gfg/test", "/home/User/Desktop/gfg/file", 
##    "/home/User/Desktop/geeks/folders" , "/home/User/Desktop/../geeks/a/folders"]


globalList = []
for i in path:

  valueInMiddle = i.split("/")[1:]
  
  if '..' in valueInMiddle:
    index = valueInMiddle.index('..')
    valueInMiddle = valueInMiddle[:index - 1] + valueInMiddle[index + 1:]
    globalList.append(valueInMiddle)

  else:
    globalList.append(valueInMiddle)

answerList = []
flag = False
for i in range(len(globalList[0])):
  valueAtHand = globalList[0][i] #home, user, desktop
  for j in range(len(globalList)):
    if globalList[j][i] != valueAtHand:
      flag = True
      break

  if flag:
    break
  
  answerList.append(valueAtHand) 

' '.join(answerList).replace(' ', '/')