17/35
Part 5 of 7 · Every suffixLearn
Walk from every start until a count is 1, and keep a later fragment only if it's shorter
Here is an insert, with a bug that gets fixed below, and the query:
# counts every visit: wrong when a fragment repeats
def add_suffixes(trie, name):
for start in range(len(name)):
node = trie
for ch in name[start:]:
node = node.setdefault(ch, {})
node[COUNT] = node.get(COUNT, 0) + 1
def shortest_fragment(trie, name):
best = None
for start in range(len(name)):
node = trie
for end in range(start, len(name)):
if best is not None and end - start + 1 >= len(best):
# can't beat best from here, and a tie keeps the earlier one
break
node = node[name[end]]
if node[COUNT] == 1:
best = name[start : end + 1]
break
return best
fragments = {}
for name in CATALOG:
add_suffixes(fragments, name)
for name in CATALOG:
print(name, shortest_fragment(fragments, name))
Among the six items, what is lamp's shortest fragment that no other name contains?
Pick one to see what it prints.
Pick an answer above to see the rest