The data structure you are looking for is called a trie. The Wikipedia article about this kind of search tree is certainly worth reading. The key property of the trie that comes in handy here is this:
All the descendants of a node have a common prefix of the string associated with that node, and the root is associated with the empty string.
The code could look as follows:
words = """py
python
co
comp
computer""".split()
def make_trie(ws):
"""Build trie from word list `ws`."""
r = {} # trie root
for w in ws:
d = r
for c in w:
d = d.setdefault(c, {}) # get c, set to {} if missing
d['$'] = '$' # end marker
return r
def num_pref(t, ws):
"""Use trie `t` to find word with max num of prefixes in `ws`."""
b, m = -1, '' # max prefixes, corresp. word
for w in ws:
d, p = t, 1
for c in w:
if '$' in d: p += 1
d = d[c] # navigate down one level
if p > b: b, m = p, w
return b, m
t = make_trie(words)
print(num_pref(t, words))
make_trie
builds the trie, num_pref
uses it to determine the word with maximum number of prefixes. It prints (3, 'computer')
.
Obviously, the two methods could be combined. I kept them separate to make the process of building a trie more clear.