ajschumacher / ajschumacher.github.io

blog
http://planspace.org/
20 stars 21 forks source link

pre-compute groups as efficiency pattern #401

Open ajschumacher opened 1 month ago

ajschumacher commented 1 month ago

instead of doing a full loop for every item, do one loop and key it into a hash

(like computing all child groups for a hierarchy, rather than scanning for children for each node)

ajschumacher commented 6 days ago
nodes = [1, 2, 3]
links = [(1, 2), (1, 3), (2, 3), (3, 1)]

groups = {node: [dest for source, dest in links
                 if node == source]
          for node in nodes}

print(groups)

groups = {}
for node in nodes:
    groups[node] = []
    for source, dest in links:
        if source == node:
            groups[node].append(dest)

print(groups)

groups = {}
for source, dest in links:
    groups.setdefault(source, []).append(dest)

print(groups)