From 8a29bdf6a6c4343c59a11ae7cb1d92dbbecffa05 Mon Sep 17 00:00:00 2001 From: Paulo Custodio Date: Wed, 11 Sep 2024 21:37:26 +0100 Subject: Add Python solution to challenge 057 --- challenge-057/paulo-custodio/python/ch-2.py | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 challenge-057/paulo-custodio/python/ch-2.py (limited to 'challenge-057/paulo-custodio/python/ch-2.py') diff --git a/challenge-057/paulo-custodio/python/ch-2.py b/challenge-057/paulo-custodio/python/ch-2.py new file mode 100644 index 0000000000..5f833663b5 --- /dev/null +++ b/challenge-057/paulo-custodio/python/ch-2.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 + +# Challenge 057 +# +# TASK #2 › Shortest Unique Prefix +# Write a script to find the shortest unique prefix for each each word in the +# given list. The prefixes will not necessarily be of the same length. +# +# Sample Input +# [ "alphabet", "book", "carpet", "cadmium", "cadeau", "alpine" ] +# Expected Output +# [ "alph", "b", "car", "cadm", "cade", "alpi" ] + +import re +import sys + +def shortest_prefix1(word, words): + for i in range(1, len(word)): + prefix = word[:i] + found = 0 + for x in words: + if re.search(r'^'+prefix, x): + found += 1 + if found == 1: + return prefix + return word + +def shortest_prefix(words): + prefixes = [] + for word in words: + prefixes.append(shortest_prefix1(word, words)) + return prefixes + +print(" ".join(shortest_prefix(sys.argv[1:]))) -- cgit