Initial commit
This commit is contained in:
commit
6099f6d242
38
README.md
Normal file
38
README.md
Normal file
@ -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 <https://tk-sls.de/wp/6071>.
|
||||
|
||||
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
|
||||
```
|
||||
|
64
trie.py
Normal file
64
trie.py
Normal file
@ -0,0 +1,64 @@
|
||||
#!/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 == '}':
|
||||
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")
|
Loading…
Reference in New Issue
Block a user