161k views
2 votes
Can someone help me out with a code. Code's in python write a function that returns the longest common prefix of two strings. For example, the longest

common prefix of distance and disinfection is dis. The header of the method is:
def prefix(s1, s2)
If the two strings have no common prefix, the method returns an empty string.
Write a main function that prompts the user to enter two strings and displays their common
prefix.
here's what I have currently but its not working.
def longestCommonPrefix(self, arr):

arr.sort(reverse = False)
print(arr)
n= len(arr)
str1 = arr[0]
str2 = arr[n-1]

n1 = len(str1)
n2 = len(str2)
result = ""
j = 0
i = 0

while(i <= n1 - 1 and j <= n2 - 1):
if (str1[i] != str2[j]):
break
result += (str1[i])

i += 1
j += 1

return (result)

User JKaz
by
5.8k points

1 Answer

4 votes

Just 10 lines of code.

from functools import reduce

list = []

def compare():

calc = [reduce(lambda a, b: a if a == b else None, x) for x in zip(*list)] + [None]

return list[0][:calc.index(None)]

list.append(input("Enter the first string: "))

list.append(input("Enter the second string: "))

print(compare())

Can someone help me out with a code. Code's in python write a function that returns-example-1
User Zahava
by
6.1k points