current position:Home>Python constructs a multitree from a dictionary
Python constructs a multitree from a dictionary
2022-06-24 08:45:09【Empty nest youth_ rui】
Python Construct a multitree from a dictionary
Subject requirements
Construct a tree node class , Each node has a int Type value (val), and 0 One or more child nodes childs.
Give a dictionary , Among them, the dictionary of key Is the current node's val,value The corresponding list corresponds to the... Of the current node childs Of val value .
Please construct the dictionary as a multi tree structure , Use root Represents the root node of the number , And print the values of each node and its child nodes .( Make sure that OrderDict The first one in the dictionary key Is the root node of the tree ).
Code implementation
from collections import defaultdict
class TreeNode(object):
def __init__(self, val=None) -> None:
self.val = val
self.childs = []
def add_childs(self, child: "TreeNode"):
self.childs.append(child)
def __repr__(self) -> str:
return str(self.val)
@classmethod
def build_tree(cls, input_dict: dict):
# Depth first traversal constructs a multi fork tree structure
def dfs(node, input_dict):
if node.val in input_dict: # When the current node has child nodes , Continue to child Construct downward
for val in input_dict[node.val]:
cur_node = TreeNode(val)
dfs(cur_node, input_dict)
node.add_childs(cur_node)
else: # The current node has no children , Go straight back to
return
# Get the first... Of the dictionary key, And take this as the root node to construct a multitree
root = TreeNode(list(input_dict.keys())[0])
dfs(root, input_dict)
return root
@classmethod
def print_tree(cls, root: "TreeNode"):
""" Print out as dictionary input """
if root:
if root.childs:
print(root.val, ": ", end="")
print('[%s]' % (' '.join([str(_.val) for _ in root.childs])))
for node in root.childs:
cls.print_tree(node)
else:
print(root.val, ": []")
@classmethod
def print_tree_graph(cls, root: "TreeNode"):
""" Print the output according to the tree level """
node_with_level = defaultdict(list)
node_with_level[0].append([root])
cur_level = 0
while node_with_level:
# Print the current layer node
cur_nodes_lists = node_with_level.pop(cur_level)
for nodes_list in cur_nodes_lists:
print(nodes_list, end=" ")
for node in nodes_list: # If there are children , Add it to the next layer
if node.childs:
node_with_level[cur_level + 1].append(node.childs)
else: # If there are no child nodes , Use [] placeholder
node_with_level[cur_level + 1].append([])
cur_level += 1
print()
input_dict = {
1: [2, 3, 4],
2: [5, 6],
3: [7],
7: [8, 9, 10],
}
tree = TreeNode.build_tree(input_dict)
TreeNode.print_tree(tree)
TreeNode.print_tree_graph(tree)
Running results :
# print_tree Method to output dictionary format results :
1 : [2 3 4]
2 : [5 6]
5 : []
6 : []
3 : [7]
7 : [8 9 10]
8 : []
9 : []
10 : []
4 : []
# print_tree_graph Method to output results in a number hierarchy format :
[1]
[2, 3, 4]
[5, 6] [7] []
[] [] [8, 9, 10]
[] [] []
For the second output format , The relationship is :
+---+
| 1 |
+-+-+
|
|
+---+-v-+---+
+----+ 2 | 3 | 4 +--+
| +---+-+-+---+ |
| | |
| | |
+-v-+---+ +v--+ +-v+
| 5 | 6 | | 7 | | |
+-+-+--++ +-+-+ +--+
| | |
| | |
+-v+ +v-+ +-v-+---+---+
| | | | | 8 | 9 | 10|
+--+ +--+ ++--+-+-+--++
| | |
| | |
+v-+ +v-+ +v-+
| | | | | |
+--+ +--+ +--+
copyright notice
author[Empty nest youth_ rui],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/175/202206240621038940.html
The sidebar is recommended
- Writing sample code for functions in Python
- Summary of operation methods of Python set (about 20 operation methods), with sample code attached
- Python -- functions
- Anonymous and recursive functions in Python
- How to query the methods (member functions) of a class or an object in Python [using the function dir()]
- Summary of operation methods of Python Dictionary (dict) (about 18 operation methods), with sample code attached
- Collect hot search lists in Python at work, which can be called a fishing artifact
- Running Django and Vue on docker
- Data classification in pandas
- About Python: docxtpl is embedded by default when inserting pictures
guess what you like
How to solve the problem of CSV? (Language Python)
Installation and use of redis (Python)
Python implements sending mail (implements single / group mail verification code)
On the built-in object type of Python -- number (one of the differences between py2 and PY3)
Python God uses a problem to help you solve the problems of formal and actual parameters in Python functions
"Project Euler Python Mini tutorial" 001-010 solution introduction
Most beginners learn Python and web automation. In this way, they learn and give up
Python matrices and numpy arrays
Exciting challenge: Python crawler crawls the cover picture of station B
After installing python3, use the yum command to report an error?
Random recommended
- New features of python3.6, 3.7, 3.8 and 3.9
- Application of Python simplehttpserver
- Python sending mail (single / group) - yagmail module
- After learning these English words, mom doesn't have to worry that I can't learn Python any more
- 1-python+ selenium automated test (detailed tutorial) in the series of exercises of "teach you by hand"
- Cannot unmarshal array into go value of type main
- Analysis of the principle of Python import
- Python quickly saves pictures in wechat official account articles (multiple articles can be specified)
- Python error reporting series (14) -- selenium support for phantom JS has been deprecated
- Python variable data type
- Advanced Python Programming - functions and modules
- Python conditional judgment and loop statements
- Python dictionary nesting
- I want to use Python to write a census management software. I want to ask about the ideas and software involved
- I want to use Python to write a census management software. I want to consult the ideas and software involved.
- Python program has no idea
- How to set the initial position of the cursor in Python Tkinter
- The scrapy framework only gets a set of results. I don't know why (Language Python)
- Code problems in Python
- Python automation framework
- Vscode - offline extension installation tutorial (take Python plug-in installation as an example)
- _ What are the application scenarios in Python
- Python writing yaml file
- On the strange phenomenon of Python objects
- System learning Python -- unit test unittest: Test Report
- Learn Python in this way, and the boss licks back the resume in the trash can: 25K per month
- Guess the age of American mathematician Wiener
- Python machine learning day03
- Random seed()
- Programming science | you may be wrong about Python
- Is Python really worth learning
- What is the charm of python, which is warmly pursued by countless programmers?
- Python is popular for several reasons: These data tell you
- Picture to character drawing in Python, so easy!
- Data type conversion in pandas module
- Python Basics - (1) overview of Python
- Data Science Library Python -- learning of time series data
- Django project - error reporting
- [run the script framework in Django and store the data in the database]
- Complete Python exception handling in ten minutes