Replace horrible flat_dict algorithm with actual recursion.

master
voussoir 2020-09-12 00:21:37 -07:00
parent ee28779138
commit 1a53af8821
1 changed files with 22 additions and 8 deletions

View File

@ -44,7 +44,7 @@ def easybake(tags, include_synonyms=True, with_objects=False):
def flat_dict(tags, include_synonyms=True): def flat_dict(tags, include_synonyms=True):
''' '''
A dictionary where every tag is its own key, and the value is a list A dictionary where every tag is its own key, and the value is a list
containing itself all of its nested children. containing itself and all of its descendants.
If synonyms are included, their key is a string, and the value is the same If synonyms are included, their key is a string, and the value is the same
list as the children of the master tag. list as the children of the master tag.
@ -60,14 +60,28 @@ def flat_dict(tags, include_synonyms=True):
for equaling the main tag versus existing in the rest of the subtree. for equaling the main tag versus existing in the rest of the subtree.
''' '''
result = {} result = {}
def recur(tag):
try:
return result[tag]
except KeyError:
pass
my_result = set()
my_result.add(tag)
for child in tag.get_children():
my_result.update(recur(child))
result[tag] = my_result
if include_synonyms:
for synonym in tag.get_synonyms():
result[synonym] = my_result
return my_result
for tag in tags: for tag in tags:
for child in tag.walk_children(): recur(tag)
children = list(child.walk_children())
result[child] = children
if not include_synonyms:
continue
for synonym in child.get_synonyms():
result[synonym] = children
return result return result
def nested_dict(tags): def nested_dict(tags):