Typing problems

Viewed 44

Hi I have binary tree and 2 functions to operate with him but I when I run mypy --disallow-any-explicit --strict I always get errors that I have no idea how to fix

class Tree:
    def __init__(self, value: str,
                 left: Optional['Tree'] = None,
                 right: Optional['Tree'] = None):
        self.value = value
        self.left = left
        self.right = right

def to_rpn(tree: Tree) -> str:
    result = ""
    if tree.value != "+" and tree.value != "*":
        return result + tree.value
    return result + (to_rpn(tree.left) + " ") + (to_rpn(tree.right) + " ") + tree.value #*

def evaluate(tree: Tree) -> int:
    if tree.value == "+":
        return int(evaluate(tree.left)) + int(evaluate(tree.right)) #*
    elif tree.value == "*":
        return int(evaluate(tree.left)) * int(evaluate(tree.right)) #*
    else:
        return int(tree.value)
  • = Argument 1 "to to_rpn"/"evaluate" has incompatible type "Optional[Tree]"; expected "Tree" (errow which i get when i run mypy on it)

I would be really grateful for any help because I spend the last 2 hours trying to solve it. Thank you!

1 Answers

You are representing the empty tree with None, so your functions have to accept an Optional[Tree] argument as well.

def to_rpn(tree: Optional[Tree]) -> str:
    ...

def evaluate(tree: Optional[Tree]) -> int:
    ...
Related