Day 7: Handy Haversacks

Functions:

parse_bagexpr(text)

Parse the expression representing a bag.

parse_rule(text)

Parse the rule from the text given as a single line.

parse_rules(lines)

Parse the rules from the given lines.

directly_contains(container, contained, rules)

Check whether the contained is contained in the container.

containers(kind, rules)

Compute the set of known containers.

count_containers(lines)

Parse the rules given as lines and count the allowed containers.

main()

Execute the main routine.

parse_bagexpr(text: str) Tuple[int, str][source]

Parse the expression representing a bag.

Returns

number of units, kind

Requires
  • re.fullmatch(r"d+ .* bags?", text)

parse_rule(text: str) Tuple[str, Dict[str, int]][source]

Parse the rule from the text given as a single line.

Returns

kind, contents

Requires
  • "n" not in text

parse_rules(lines: Lines) Dict[str, Dict[str, int]][source]

Parse the rules from the given lines.

directly_contains(container: str, contained: str, rules: Dict[str, Dict[str, int]]) bool[source]

Check whether the contained is contained in the container.

containers(kind: str, rules: Dict[str, Dict[str, int]]) Set[str][source]

Compute the set of known containers.

Ensures
  • all(
        not directly_contains(non_container, container, rules)
        for non_container in (rules.keys() - result)
        for container in result
    )
    

    (Nothing else contains anything in the result)

  • kind in result

    (given kind is in the result)

count_containers(lines: Lines) int[source]

Parse the rules given as lines and count the allowed containers.

main() None[source]

Execute the main routine.