DEV Community

Discussion on: Daily Coding Problem #3

Collapse
 
heptasean profile image
Benjamin Braatz • Edited

Python solution defining __repr__, which is meant for exactly this purpose:

class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

    def __repr__(self):
        return ( 'Node(' + repr(self.val) + ', '
                         + repr(self.left) + ', '
                         + repr(self.right) + ')' )

    def __eq__(self, other):
        if isinstance(other, Node):
            return ( self.val == other.val and
                     self.left == other.left and
                     self.right == other.right )
        return False

    def __hash__(self):
        return hash((self.val, self.left, self.right))

serialise = repr
deserialise = eval

node = Node('root', Node('left', Node('left.left')), Node('right'))
assert deserialise(serialise(node)).left.left.val == 'left.left'
assert deserialise(serialise(node)) == node
assert hash(deserialise(serialise(node))) == hash(node)

Edit: Included test from problem statement in the code, so that it should now be ready for copy and paste into file and python3 -i <file>. While we are at it, implemented __eq__ and __hash__, so that we can assert even stronger tests.

Collapse
 
solomonli profile image
Solomon Li ✊YOLO🙃

Quite impressive, thank you!