Program for longest common directory path in Python

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the longest common path from the given list of paths. Let's see an example to understand the problem statement more clearly.

Input

paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorialspoint/javascript',
'home/tutorialspoint/react', 'home/tutorialspoint/django']
/home/tutorialspoint/

We can solve the problem using os module very easily. Let's see the steps to solve the

  • Import the os module.
  • Initialize the list of paths to find the longest common path.
  • Find the common prefix of all paths using os.path.commonprefix(paths) and store it in variable.
  • And extract the directory from the common prefix using os.path.dirname(common_prefix).

Example

 Live Demo

# importing the os module
import os
# initializing the paths
paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorials
point/javascript', 'home/tutorialspoint/react', 'home/tutorialspoint/django']
# finding the common prefix
common_prefix = os.path.commonprefix(paths)
# extracting the directory from the common prefix
longest_common_directory = os.path.dirname(common_prefix)
# printing the long common path
print(longest_common_directory)

Output

If you run the above code, then you will get the following result.

home/tutorialspoint

Conclusion

If you have any queries regarding the tutorial, mention them in the comment section.

raja
Updated on 06-Jul-2020 09:28:32

Advertisements