trie/trie.py

65 lines
1.4 KiB
Python
Executable File

#!/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:
if k == '{' or k == ',' or k == '}' or k == ' ':
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")