aboutsummaryrefslogtreecommitdiff
path: root/challenge-057/paulo-custodio/python/ch-2.py
blob: 5f833663b53a205d25c896561531e97a54565e63 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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:])))