Python solution defining __repr__, which is meant for exactly this purpose:
__repr__
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.
python3 -i <file>
__eq__
__hash__
Quite impressive, thank you!
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Python solution defining
__repr__
, which is meant for exactly this purpose: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.Quite impressive, thank you!