Python code for longest common subdirectory in given path list

489 Views Asked by At

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.

1

There are 1 best solutions below

0
nitesh mishra On
### 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(' ', '/')