commit 6099f6d242f1e282d9e26196f68c0e371e1ab150 Author: Tilman Kranz Date: Sat Aug 20 09:51:37 2022 +0200 Initial commit diff --git a/README.md b/README.md new file mode 100644 index 0000000..11b6b6e --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +# Transform Set of Strings to Common Prefix Notation + +## Description + +Presented with a series of lines on standard input, the program will +print an expression on standard output that denotes the line strings +in a syntax described in . + +The expression is suitable for Bourne Again Shell brace expansion. + +## Test + +``` +$ python3 trie.py << EOF +a +ab +abc +EOF +``` + +Expected output: + +``` +a{,b{,c}} +``` + +Test if the output is accurate: + +``` +$ bash -c 'echo a{,b{,c}}' +``` + +Expected output: + +``` +a ab abc +``` + diff --git a/trie.py b/trie.py new file mode 100644 index 0000000..6ad1d86 --- /dev/null +++ b/trie.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# author: Tilman Kranz +# license: MIT License +# 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 == '}': + 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")