|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import sys |
| 3 | +import re |
| 4 | +from typing import List, Set |
| 5 | +import networkx as nx |
| 6 | + |
| 7 | +def count_bags(graph, node): |
| 8 | + number = 1 |
| 9 | + for subnode, amount in G[node].items(): |
| 10 | + print(subnode, amount) |
| 11 | + subnum = count_bags(G, subnode) |
| 12 | + number += amount['num'] * subnum |
| 13 | + print(subnum, number) |
| 14 | + return number |
| 15 | + |
| 16 | +if __name__ == "__main__": |
| 17 | + G = nx.DiGraph() |
| 18 | + with open(sys.argv[1], "r") as infile: |
| 19 | + for nextline in infile: |
| 20 | + search = "(?P<amount>[0-9])+\ (?P<color>[a-z]*\ [a-z]*)\ bag[s]?" |
| 21 | + left, right = nextline.strip().split("bags contain") |
| 22 | + left = left.strip() |
| 23 | + right = right.strip() |
| 24 | + matches = re.finditer(search, right) |
| 25 | + G.add_node(left) |
| 26 | + for m in matches: |
| 27 | + amount = int(m.group("amount")) |
| 28 | + color = m.group("color") |
| 29 | + #G.add_node(color) |
| 30 | + G.add_edge(left, color, num=int(amount)) |
| 31 | + |
| 32 | + print("Part 1: ", len(nx.ancestors(G, 'shiny gold'))) |
| 33 | + print(nx.descendants(G, 'shiny gold')) |
| 34 | + print(G['shiny gold']) |
| 35 | + print(count_bags(G, 'shiny gold')) |
| 36 | + # print(nx.dfs_predecessors(G,"shiny gold")) |
| 37 | + # print(nx.dfs_successors(G,"shiny gold")) |
| 38 | + # print(len(nx.dfs_predecessors(G,"shiny gold"))) |
| 39 | + # print(list(nx.edge_dfs(G,'shiny gold', orientation='reverse'))) |
| 40 | + # print(list(nx.dfs_edges(G,'shiny gold'))) |
| 41 | + |
| 42 | + # print( |
| 43 | + # "part 1: ", |
| 44 | + # sum([check_group(group) for group in groups]), |
| 45 | + # " answered yes", |
| 46 | + # ) |
| 47 | + # print( |
| 48 | + # "part 2: ", |
| 49 | + # sum([check_group(group, False) for group in groups]), |
| 50 | + # " answered yes", |
| 51 | + # ) |
0 commit comments