I am looking for the longest common prefix and my code isnt working as I would like it to. It can detect prefix in every list below (list one to seven, except four):
four = ["a", "a", "b"]
there is no common prefix but my program returns "a". I need to get "". How can I fix this, please? (I'm learning to code :-))
My code:
one = ["aac", "aab", "aabb"] #aa
two = ["a", "a"] #a
three = ["a"] #a
four = ["a", "a", "b"] #is "" but i get "a"
five = ["aaaa", "bbb", "ccc"] #""
six = ["marmelada", "marketa", "marek"] #mar
seven = ["", "", ""] #""
def check_prefix(words):
for i in range(1, len(words[0])+1):
if len(words) == 1:
return words[0]
for j in words[1:]:
if i == len(words[0]) and words[0][:i] == j[:i]:
return words[0][:i]
if words[0][:i] != j[:i]:
return words[0][:i-1]
return ""
print(check_prefix(one))
print(check_prefix(two))
print(check_prefix(three))
print(check_prefix(four))
print(check_prefix(five))
print(check_prefix(six))
print(check_prefix(seven))
I trid to use module os as os.path.commonprefix() and this worked well for me. However I would like to fix my code.