Last active
February 11, 2024 03:42
-
-
Save divi255/9c5b2fa0ffa7a282f6408c0bf0dfcc0b to your computer and use it in GitHub Desktop.
tags to tree Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from bma_benchmark import benchmark | |
def tags_to_tree(tags): | |
def fill_tags_tree_recursive(tag, tree): | |
ch = tag.split('.', maxsplit=1) | |
if len(ch) == 1: | |
tree[tag] = {} | |
else: | |
fill_tags_tree_recursive(ch[1], tree.setdefault(ch[0], {})) | |
tags_tree = dict() | |
for tag in tags: | |
fill_tags_tree_recursive(tag, tree=tags_tree) | |
return tags_tree | |
def tree_to_tags(tree): | |
tags = [] | |
def combine_tags_tree_recursive(tree, prefix): | |
for key, members in tree.items(): | |
if members: | |
combine_tags_tree_recursive(members, prefix.copy() + [key]) | |
else: | |
tags.append('.'.join(prefix + [key])) | |
combine_tags_tree_recursive(tree, []) | |
return tags | |
tags = [] | |
for a in range(0, 10): | |
for b in range(0, 10): | |
for c in range(0, 10): | |
for d in range(0, 10): | |
for e in range(0, 10): | |
tags.append( | |
f"tagname_a{a}.tagname_b{b}.tagname_c{c}.tagname_d{d}.tagname_e{e}" | |
) | |
@benchmark(base=True) | |
def bench_tree(): | |
global tags | |
tree = tags_to_tree(tags) | |
tags_new = tree_to_tags(tree) | |
assert len(tags_new) == len(tags) | |
print(len(tags)) | |
benchmark.run(number=1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment