Skip to content

Commit eaa02af

Browse files
authored
Merge pull request #659 from sravanyabendi/longest-common-prefix
Implementation of LongestCommonPrefix in Python
2 parents ad27fa1 + c33dc20 commit eaa02af

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#Longest Common Prefix in python
2+
#Implementation of python program to find the longest common prefix amongst the given list of strings.
3+
#If there is no common prefix then returning 0.
4+
5+
#define the function to evaluate the longest common prefix
6+
def longestCommonPrefix(s):
7+
p = '' #declare an empty string
8+
for i in range(len(min(s, key=len))):
9+
f = s[0][i]
10+
for j in s[1:]:
11+
if j[i] != f:
12+
return p
13+
p += f
14+
return p #return the longest common prefix
15+
16+
17+
n = int(input("Enter the number of names in list for input:"))
18+
print("Enter the Strings:")
19+
s = [input() for i in range(n)]
20+
if(longestCommonPrefix(s)):
21+
print("The Common Prefix is:" ,longestCommonPrefix(s))
22+
else:
23+
print("There is no common prefix for the given list of strings, hence the answer is:", 0)

0 commit comments

Comments
 (0)