I a little bit confused about this one liner
tree = lambda: defaultdict(tree)
How it is possible? (lambda should return default dict but how we can put first arg as tree?)
Lambdas delay evaluation of their contents until they are called, so when tree() is called and defaultdict(tree) is evaluated, tree will be well defined, and thus not cause any issues. A more explicit example:
>>> foo = lambda: bar
>>> foo()
NameError: global name 'bar' is not defined
>>> bar = 5
>>> foo()
5
As for what this particular lambda does: The first argument to defaultdict is a factory method used when a key is missing(see documentation for details). So the one-liner
tree = lambda: defaultdict(tree)
defines a dictionary that by default contains other dictionaries. I.e. a tree.
For example:
my_tree = tree()
creates a new tree, and the following two lines do the same thing:
my_tree["foo"]
my_tree["foo"] = defaultdict(tree)
Namely creating a new subtree named "foo". New elements can thus be added deep into the tree without creating each subtree manually. For example:
root = tree()
root["foo"]["bar"]["baz"] = False
tree = lambda: bananaramais valid, up until you call it and the lookup onbananaramafails.