Day 16: Ticket Translation

Classes:

RuleParsing(identifier, ranges)

Represent a rule which is not constrained by pre-conditions.

Rule(identifier, ranges)

Represent a rule for the ticket field.

Functions:

applies(rule, value)

Check whether the rule applies to the value.

parse_rules(lines)

Parse the lines into rules.

parse_nearby_tickets(lines)

Parse the nearby tickets from lines to list of field values.

invalid_fields(rules, ticket)

Select the invalid fields from a ticket according to rules.

list_all_invalid_values(rules, tickets)

Select the invalid fields accross all tickets according to rules.

compute_error_rate(invalid_values)

Compute the error rate as sum of the invalid values.

class RuleParsing(identifier: str, ranges: List[Tuple[int, int]])[source]

Represent a rule which is not constrained by pre-conditions.

Methods:

__init__(identifier, ranges)

Initialize with the given values.

Attributes:

identifier

Identifier of the field

ranges

Valid range of values for the field

__init__(identifier: str, ranges: List[Tuple[int, int]]) None[source]

Initialize with the given values.

identifier: Final[str]

Identifier of the field

ranges: Final[List[Tuple[int, int]]]

Valid range of values for the field

class Rule(identifier: str, ranges: List[Tuple[int, int]])[source]

Represent a rule for the ticket field.

Methods:

__init__(identifier, ranges)

Initialize with the given values.

Attributes:

identifier

identifier of the field

ranges

acceptable ranges for the field

__init__(identifier: str, ranges: List[Tuple[int, int]]) None[source]

Initialize with the given values.

Requires
  • all(range[0] < range[1] for range in ranges)

  • len(identifier) > 0

identifier: Final[str]

identifier of the field

ranges: Final[List[Tuple[int, int]]]

acceptable ranges for the field

applies(rule: Rule, value: int) bool[source]

Check whether the rule applies to the value.

parse_rules(lines: Lines) List[RuleParsing][source]

Parse the lines into rules.

While the parsed rules are syntactically correct, they have to be yet semantically verified.

Requires
  • all(RULE_RE.match(line) for line in lines)

parse_nearby_tickets(lines: List[str]) List[List[int]][source]

Parse the nearby tickets from lines to list of field values.

Requires
  • all(
        re.match(r'^(0|[1-9][0-9]*)(,(0|[1-9][0-9]*))+\Z', line)
        for line in lines
    )
    
invalid_fields(rules: List[Rule], ticket: List[int]) List[int][source]

Select the invalid fields from a ticket according to rules.

Ensures
  • all(
        value in ticket
        for value in result
    )
    
list_all_invalid_values(rules: List[Rule], tickets: List[List[int]]) List[int][source]

Select the invalid fields accross all tickets according to rules.

Ensures
  • all(
        any(value in ticket for ticket in tickets)
        for value in result
    )
    
compute_error_rate(invalid_values: List[int]) int[source]

Compute the error rate as sum of the invalid values.