
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program for longest common directory path in Python
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
# 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.
- Related Articles
- SequenceMatcher in Python for Longest Common Substring.
- C++ Program for Longest Common Subsequence
- Java Program for Longest Common Subsequence
- Longest Common Prefix in Python
- Program to find length of longest matrix path length in Python
- Program to find length of longest path with even sum in Python
- Longest Increasing Path in a Matrix in Python
- Program to length of longest increasing path in a given matrix in Python
- Program to find longest even value path of a binary tree in Python
- Program to find longest path between two nodes of a tree in Python
- Program to find longest common prefix from list of strings in Python
- Python Program for Min Cost Path
- Program to find length of longest consecutive path of a binary tree in python
- Program to find length of longest alternating path of a binary tree in python
- Program to find length of longest common subsequence of three strings in Python

Advertisements