Skip to content

Commit 875102c

Browse files
committed
Implementation of LongestCommonPrefix in Python
1 parent 424cdbb commit 875102c

File tree

1 file changed

+21
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)