diff --git a/pygorithm/strings/longest_common_prefix.py b/pygorithm/strings/longest_common_prefix.py new file mode 100644 index 0000000..aeb2086 --- /dev/null +++ b/pygorithm/strings/longest_common_prefix.py @@ -0,0 +1,42 @@ +''' +Author : Nitish Kumar (nitish771) +25-06-21 +''' + +from inspect import getsource + + +def common_word(word1, word2): + result = '' + l1 = len(word1) + l2 = len(word2) + min_len = l1 if l1 < l2 else l2 + for i in range(min_len): + if word1[i] != word2[i]: + break + result += word1[i] + return result + + +def longest_prefix(words: list) -> str: + """ + Args: + words : List of words (min lenght = 1) + Return: + str + """ + + if len(words) == 1: + return words[0] + + if not len(words): + return 'Please give me a list of words' + + ans = words[0] + for word in words: + ans = common_word(ans, word) + return ans + + +def get_code(): + return getsource(longest_prefix) diff --git a/tests/test_string.py b/tests/test_string.py index 7701c00..5cd89df 100644 --- a/tests/test_string.py +++ b/tests/test_string.py @@ -5,7 +5,10 @@ isogram, pangram, manacher_algorithm, - palindrome) + palindrome, + longest_common_prefix, +) + class TestAnagram(unittest.TestCase): def test_anagram(self): @@ -30,5 +33,10 @@ class TestManacherAlgorithm(unittest.TestCase): def test_manacher_algorithm(self): self.assertEqual(manacher_algorithm.manacher('babcbabcbaccba'), 'abcbabcba') +class TestLongestCommonPrefix(unittest.TestCase): + def test_common_prefix(self): + words = ["hi", "hid", "hidden", "hideous"] + self.assertEqual(longest_common_prefix.longest_prefix(words), "hi") + if __name__ == '__main__': unittest.main()