2022-08-20 09:51:37 +02:00
|
|
|
#!/usr/bin/env python
|
|
|
|
# author: Tilman Kranz <t.kranz@tk-sls.de>
|
|
|
|
# license: MIT License <https://opensource.org/licenses/MIT>
|
|
|
|
# summary: Transform a series of lines into a common prefix notation.
|
|
|
|
import sys
|
|
|
|
|
|
|
|
# thanks: https://www.adamsmith.haus/python/answers/how-to-create-a-trie-in-python
|
|
|
|
def construct_trie(word_list):
|
|
|
|
root = dict()
|
|
|
|
for word in word_list:
|
|
|
|
level = root
|
|
|
|
l = len(word)
|
|
|
|
last = l - 1
|
|
|
|
|
|
|
|
for i in range(l):
|
|
|
|
letter = word[i]
|
|
|
|
if letter not in level:
|
|
|
|
level[letter] = dict()
|
|
|
|
if i == last:
|
|
|
|
level[letter][''] = dict()
|
|
|
|
level = level[letter]
|
|
|
|
|
|
|
|
return root
|
|
|
|
|
|
|
|
def print_trie(trie):
|
|
|
|
length = len(trie)
|
|
|
|
|
|
|
|
if length == 0:
|
|
|
|
return
|
|
|
|
|
|
|
|
if length > 1:
|
|
|
|
sys.stdout.write("{")
|
|
|
|
|
|
|
|
count = 1
|
|
|
|
|
|
|
|
for k in trie:
|
2022-08-21 15:47:44 +02:00
|
|
|
if k == '{' or k == ',' or k == '}' or k == ' ':
|
2022-08-20 09:51:37 +02:00
|
|
|
sys.stdout.write('\\')
|
|
|
|
|
|
|
|
sys.stdout.write(k)
|
|
|
|
|
|
|
|
print_trie(trie[k])
|
|
|
|
|
|
|
|
if count < length:
|
|
|
|
sys.stdout.write(",")
|
|
|
|
|
|
|
|
count += 1
|
|
|
|
|
|
|
|
if length > 1:
|
|
|
|
sys.stdout.write("}")
|
|
|
|
|
|
|
|
lines = []
|
|
|
|
|
|
|
|
for line in sys.stdin:
|
|
|
|
stripped = line.strip()
|
|
|
|
|
|
|
|
if stripped != "":
|
|
|
|
lines.append(stripped)
|
|
|
|
|
|
|
|
trie = construct_trie(lines)
|
|
|
|
# -DEBUG- Dump trie datastructure to standard output.
|
|
|
|
# print(trie)
|
|
|
|
print_trie(trie)
|
|
|
|
sys.stdout.write("\n")
|