leavestrie.py (881B)
1 #!/usr/bin/env python3 2 3 """Read json trie in stdin, produce leaves and values 4 argv[1] is 1 or -1 to reverse the label sequence or not""" 5 6 import json 7 import sys 8 9 trie = json.load(sys.stdin) 10 11 def leaves(trie, prefix="", provisional=None): 12 """Keep only the most probable values at each node""" 13 if len(trie[1].keys()) == 0: 14 assert(len(trie[0].keys()) == 1) 15 k, v = trie[0].popitem() 16 if (k != provisional): 17 # does not agree with provisional decision so far 18 print("%s\t%s" % (k, prefix[::int(sys.argv[1])])) 19 # decided nodes 20 if len(trie) == 3 and trie[2]: 21 if (trie[2] != provisional): 22 # does not agree with provisional decision so far 23 print("%s\t%s" % (trie[2], prefix[::int(sys.argv[1])])) 24 if len(trie) == 3: 25 provisional = trie[2] 26 for child in trie[1].keys(): 27 leaves(trie[1][child], prefix + child, provisional) 28 29 leaves(trie) 30