compresstrie.py (753B)
1 #!/usr/bin/env python3 2 3 """Read json trie in stdin, trim unneeded branches and output json dump 4 to stdout""" 5 6 import json 7 import sys 8 9 trie = json.load(sys.stdin) 10 11 def compress(trie): 12 """Compress the trie""" 13 ref = None 14 num = 0 15 ok = True 16 if trie[0] != {}: 17 if len(trie[0].keys()) > 1: 18 return None 19 ref = list(trie[0].keys())[0] 20 num = trie[0][ref] 21 for child in trie[1].values(): 22 x = compress(child) 23 if not ok or x == None: 24 ok = False 25 continue 26 r, n = x 27 if ref == None: 28 ref = r 29 if ref != r: 30 ok = False 31 num += n 32 if not ok: 33 return None 34 trie[0] = {} 35 trie[0][ref] = num 36 trie[1] = {} 37 #print(ref, file=sys.stderr) 38 return ref, num 39 40 compress(trie) 41 42 print(json.dumps(trie)) 43