When encountering some algorithms that involve arrays (such as sorting or statistics), the visualization of arrays can provide us with a more intuitive perspective to find bugs in our own programs (or learn the implementation principles of certain algorithms) .
Here is an array visualization class that I wrote for beginners. In order to reduce the difficulty and reduce the cost, I castrated a lot of secondary content.
In this code, I provide the corresponding interface, which allows other programmers to directly import my code file and expand it.
Method to realize
1 goal
Visualize the array
2 Implementation principle
Use Matplotlib to set the index of the array as xxx axis, the corresponding value isyyThe y- axis is then plotted as a histogram.
3 concrete realization
The library used is
import matplotlib.pyplot as plt
3.1 Initialization
Here, use the plt.subplots() method to initialize a canvas, and store the returned fig and ax variables in the class for encapsulation, which is convenient for subsequent expansion.
class VisualArray():
"""动态可视化数组"""
def __init__(self):
"""初始化"""
self.fig,self.ax = plt.subplots()
3.2 Drawing an image
The method of drawing a chart is to erase the image of the previous frame, and then draw the image of the next frame.
The bar method is used here to draw, and some basic display parameters are drawn to facilitate programmers to adjust the effect.
By default, the animation will disappear after drawing, so if you want to keep the last frame of image or end the animation early, you can use plt.show() . For convenience, this function is also specially encapsulated as a method.
def stop(self):
"""结束绘画,使图片保留在最后一帧"""
plt.show()
3.4 Analysis
This is a memoryless abstract data type, that is, each frame in this visualization class will not be affected by the previous display content (although you seem to be affected). Therefore, the space cost is a constant level.
Except for the ax.bar() method which is greatly affected by the array, the rest of the statements can be completed in constant time , so the method is analyzed separately, in the case of a fixed array size:
it can be seen that in addition to the equal frequency Except for the sharp point, the time cost at other times is constant.
Analyzing the dynamically changing array, there are:
after eliminating the interference of abnormal points, the time cost in the case of the dynamic array is linear.
Complete code
You can store this code separately in a .py and then call it. Just write this on the file that calls the code.
import 代码名称
Note that the two code files must be placed in the same file!