Day 18: Operation Order

Classes:

Operation(value)

Represent a mathematical operation.

Tail(op, right)

Represent the tail of an expression.

Node(head, tail)

Represent a node of the abstract syntax tree of a mathematical expression.

Functions:

extract_expression(expr)

Extract the sub-expression surrounded by parentheses in expr.

parse(expression)

Parse the expression into an abstract syntax tree.

serialize(node)

Serialize the abstraction syntax tree given as node to a string.

compute(node)

Evaluate the parsed expression given as node.

class Operation(value)[source]

Represent a mathematical operation.

Attributes:

ADD

Addition

MUL

Multiplication

ADD = '+'

Addition

MUL = '*'

Multiplication

class Tail(op: Operation, right: Union[int, Node])[source]

Represent the tail of an expression.

Attributes:

op

Operation of the mathematical expression

right

Right-hand side of the expression

Methods:

__delattr__(name)

Implement delattr(self, name).

__eq__(other)

Return self==value.

__init__(op, right)

__repr__()

Return repr(self).

__setattr__(name, value)

Implement setattr(self, name, value).

op: Operation

Operation of the mathematical expression

right: Union[int, Node]

Right-hand side of the expression

__delattr__(name)

Implement delattr(self, name).

__eq__(other)

Return self==value.

__init__(op: Operation, right: Union[int, Node]) None
__repr__()

Return repr(self).

__setattr__(name, value)

Implement setattr(self, name, value).

class Node(head: Union[int, Node], tail: List[Tail])[source]

Represent a node of the abstract syntax tree of a mathematical expression.

Attributes:

head

Constant or left-hand side expression

tail

Remaining expressions on the right-hand side

Methods:

__delattr__(name)

Implement delattr(self, name).

__eq__(other)

Return self==value.

__init__(head, tail)

__repr__()

Return repr(self).

__setattr__(name, value)

Implement setattr(self, name, value).

head: Union[int, Node]

Constant or left-hand side expression

tail: List[Tail]

Remaining expressions on the right-hand side

__delattr__(name)

Implement delattr(self, name).

__eq__(other)

Return self==value.

__init__(head: Union[int, Node], tail: List[Tail]) None
__repr__()

Return repr(self).

__setattr__(name, value)

Implement setattr(self, name, value).

extract_expression(expr: str) str[source]

Extract the sub-expression surrounded by parentheses in expr.

Requires
  • expr.count("(") == expr.count(")")

  • re.match(r"^(.+)", expr)

Ensures
  • result in expr

parse(expression: str) Optional[Node][source]

Parse the expression into an abstract syntax tree.

serialize(node: Node) str[source]

Serialize the abstraction syntax tree given as node to a string.

Ensures
  • parse(result) == node

compute(node: Node) int[source]

Evaluate the parsed expression given as node.