One line of Python code to implement tree structure

Tree structure is an abstract data type that has a very wide range of applications in computer science. A tree can be represented simply as the root, the left subtree, and the right subtree. The left and right subtrees can have their own subtrees. This seems to be a relatively complex data structure, so can it really be implemented with a single line of Python code as we said in the title?

One line of code to achieve?

Since the outer and inner layers of the tree structure have similar structures, the tree can be defined recursively. Using what's available in Python defaultdict, we can easily define trees with just one line of code.

from collections import defaultdict

def tree(): return defaultdict(tree)

This code is shared from https://gist.github.com/hrldcpr/2012250 . According to the above code, a tree is a dictionary whose default value is also tree.

Demonstration of specific effects

There are two wonderful things about the tree implemented in this way, the first is that we don't need to create nodes, we can reference them directly. E.g:

users = tree()
users['codingpy']['username'] = 'earlgrey'
users['python']['username'] = 'Guido van Rossum'

If we only look at the characteristics of regular dictionaries, the above assignment operation is not valid, because we must declare it in advance users['codingpy'] = {}. But we're using a class collectionsin the module, defaultdictand if a key doesn't exist, it's used to create an initial value for tree()that key, since tree is provided defaultdict. According to the documentation , if this parameter is provided, the value of the parameter is passed to the constructor as the first parameter.default_factorydefaultdict

If we print the above code in json format (ie pass print(json.dumps(users))), we will get the following result:

{"codingpy": {"username": "earlgrey"}, "python": {"username": "Guido van Rossum"}}

The second point is that we don't even need to perform assignment operations like the above, we just need to reference to create a tree. E.g:

categories = tree()

categories['Programming Languages']['Python']
categories['Python']['Standard Library']['sys']
categories['Python']['Standard Library']['os']

If we continue to run print(json.dumps(categories)), we get the following result:

{"Python": {"Standard Library": {"sys": {}, "os": {}}}, "Programming Languages": {"Python": {}}}

The second magic, also known as Autovivification , first appeared in Perl, refers to the automatic creation of an array when it is referenced. Python itself does not support this feature, but it can be defaultdictimitated as described in this article.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326420713&siteId=291194637