The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 41 Python Common Composite Data Types - Queues (FIFO, LIFO, Priority Queue, Double-Ended Queue, and Ring Queue)
Abstracts:
In Python, a queue is a commonly used data structure for storing and accessing data in a particular order. The main types of queues include First-In-First-Out (FIFO), Last-In-First-Out (LIFO), Priority Queue, Double-Ended Queue (Deque), and Ring Queue, each of which has its own unique uses in different application scenarios.
Link to original article:
FreakStudio's Blog
Past Recommendations:
You're learning embedded and you don't know how to be object oriented?
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 00 Introduction to Object-Oriented Design Methods
The network's most suitable for the introduction of object-oriented programming tutorials: 01 Basic Concepts of Object-Oriented Programming
The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 02 Python Implementations of Classes and Objects - Creating Classes with Python
The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 03 Python Implementations of Classes and Objects - Adding Attributes to Custom Classes
The Best Object-Oriented Programming Tutorial on the Net for Getting Started: 04 Python Implementation of Classes and Objects - Adding Methods to Custom Classes
The Best Object-Oriented Programming Tutorial on the Net for Getting Started: 05 Python Implementation of Classes and Objects - PyCharm Code Tags
The best object-oriented programming tutorials on the net for getting started: 06 Python implementation of classes and objects - data encapsulation of custom classes
The best object-oriented programming tutorial on the net for getting started: 07 Python implementation of classes and objects - type annotations
The best object-oriented programming tutorials on the net for getting started: 08 Python implementations of classes and objects - @property decorator
The best object-oriented programming tutorials on the net for getting started: 09 Python implementation of classes and objects - the relationship between classes
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 10 Python Implementations of Classes and Objects - Class Inheritance and Richter's Replacement Principle
The best object-oriented programming tutorials on the net for getting started: 11 Python implementation of classes and objects - subclasses call parent class methods
The network's most suitable for the introduction of object-oriented programming tutorials: 12 classes and objects of the Python implementation - Python using the logging module to output the program running logs
The network's most suitable for the introduction of object-oriented programming tutorials: 13 classes and objects of the Python implementation - visual reading code artifacts Sourcetrail's installation use
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 14 Python Implementations of Classes and Objects - Static Methods and Class Methods for Classes
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 15 Python Implementations of Classes and Objects - __slots__ Magic Methods
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 16 Python Implementations of Classes and Objects - Polymorphism, Method Overriding, and the Principle of Open-Close
The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 17 Python Implementations of Classes and Objects - Duck Types and "file-like objects"
The network's most suitable for the introduction of object-oriented programming tutorials: 18 classes and objects Python implementation - multiple inheritance and PyQtGraph serial data plotting graphs
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 19 Python Implementations of Classes and Objects - Using PyCharm to Automatically Generate File Annotations and Function Annotations
The best object-oriented programming tutorials on the web for getting started: 20 Python implementation of classes and objects - Combinatorial relationship implementation and CSV file saving
The best introductory object-oriented programming tutorials on the net: 21 Python implementation of classes and objects - Organization of multiple files: modulemodule and packagepackage
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 22 Python Implementations of Classes and Objects - Exceptions and Syntax Errors
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 23 Python Implementation of Classes and Objects - Throwing Exceptions
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 24 Python Implementations of Classes and Objects - Exception Catching and Handling
The best object-oriented programming tutorials on the web for getting started: 25 Python implementation of classes and objects - Python to determine the type of input data
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 26 Python Implementations of Classes and Objects - Context Managers and with Statements
The best introductory object-oriented programming tutorials on the web: 27 Python implementation of classes and objects - Exception hierarchy and custom exception class implementation in Python
The best object-oriented programming tutorials on the net for getting started: 28 Python implementations of classes and objects - Python programming principles, philosophies and norms in a big summary
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 29 Python Implementations of Classes and Objects - Assertions and Defensive Programming and Use of the help Function
The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 30 Python's Built-In Data Types - the root class of object
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 31 Python's Built-In Data Types - Object Object and Type Type
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 32 Python's Built-in Data Types - Class Class and Instance Instance
The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 33 Python's Built-In Data Types - The Relationship Between the Object Object and the Type Type
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 34 Python's Built-In Data Types - Python's Common Compound Data Types: Tuples and Named Tuples
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 35 Python's Built-In Data Types - Document Strings and the __doc__ Attribute
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 36 Python's Built-In Data Types - Dictionaries
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 37 Python's Common Composite Data Types - Lists and List Derivatives
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 38 Python's Common Composite Data Types - Using Lists to Implement Stacks, Queues, and Double-Ended Queues
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 39 Python Common Composite Data Types - Collections
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 40 Python's Common Compound Data Types - Enumeration and Use of the enum Module
More highlights to watch:
Accelerating Your Python: A Quick Guide to Python Parallel Computing
Understanding CM3 MCU Debugging Principles in One Article
Liver half a month, embedded technology stack summary out of the big
The "Secrets of the Martial Arts" of the Computer Competition
A MicroPython open source project collection: awesome-micropython, including all aspects of Micropython tool library
Avnet ZUBoard 1CG Development Board - A New Choice for Deep Learning
SenseCraft Deploys Models to Grove Vision AI V2 Image Processing Module
Documentation and code acquisition:
The following link can be accessed to download the document:
/leezisheng/Doc
This document mainly introduces how to use Python for object-oriented programming, which requires readers to have a basic understanding of Python syntax and microcontroller development. Compared with other blogs or books that explain Python object-oriented programming, this document is more detailed and focuses on embedded host computer applications, with common serial port data sending and receiving, data processing, and dynamic graph drawing as application examples for the host computer and the lower computer, and using Sourcetrail code software to visualize and read the code for readers' easy understanding.
The link to get the relevant sample code is below:/leezisheng/Python-OOP-Demo
main body (of a book)
Queue as a special data structure, like a collection, can be fully realized by the list to achieve its function. Queue is a special kind of linear table, its particularity is only allowed in the front end of the deletion operation, while in the back end of the insertion operation, which is similar to the behavior pattern of the stack, is a kind of restricted linear table. The end of the insertion operation is called the end of the queue, and the end of the deletion operation is called the head of the queue, and the core concept is "first-in, first-out".
The Queue module in Python provides a synchronous, thread-safe queue class that includes the common FIFO (first-in, first-out), LIFO (last-in, first-out), PriorityQueue, and SimpleQueue, a first-in, first-out type.
The basic operation of a queue is as follows:
methodologies | descriptive |
---|---|
() | Returns the size of the queue. |
() | If the queue is empty, return True, otherwise False. |
() | Returns True if the queue is full, and False if it is not. |
([block[, timeout]]) | Get queue, timeout wait time. |
Q.get_nowait() | Equivalent to (False), a non-blocking method. |
(item) | Write to queue, timeout wait time. |
Q.task_done() | The task_done() call tells the queue that the task has been processed. |
() | In practice this means waiting until the queue is empty before performing another operation |
FIFO queue
FIFO, or First In First Out, is the most common definition of a queue. Imagine a queue at a bank or cash machine, where the person at the front of the line is usually the first to be served, and the people at the back of the line are served in turn, as is the case with Python's Queue class.
The Queue class is often used as a communication medium of some sort when some objects produce data and other objects need to consume that data, and possibly at different rates. Imagine a messaging application that receives messages from the network, but can only present one message to the user at a time. The other messages are cached in a queue in the order they are received.
The Queue class becomes an ideal choice when considering that the data in the data structure needs to be accessed only when the next object is consumed. In this case, using a list would be inefficient because inserting (or removing) data at the head of the list would require moving all remaining elements.
import queue
# If you don't set the length, the default is infinite.
q = (5)
# Note the lack of parentheses
print()
(123)
(456)
(789)
(100)
print(())
print(())
print(())
The results of the run are as follows:
LIFO queue
LIFO stands for Last In First Out, and LIFO queues are often referred to as stacks.Think we can use a stack of paper as a figurative analogy, where you can only get to the top sheet at a time. You can put another piece of paper on top to make it the top one, or you can take away the top one to reveal the bottom one.
By convention, operations on a stack are called push and pop, but Python's queue module uses exactly the same API as a FIFO queue: put() and get(). Except that in a LIFO queue, these methods work on the "top" of the stack instead of the front and back of the queue.(In fact, LIFO and FIFO queues inherit from the same parent class and implement different operations in the same methods, which is a very good example of polymorphism in object-oriented programming that we talked about earlier.)
LIFO queue in the underlying implementation is a standard list , compared to the list , Lifo queue supports multi-threaded concurrent access , while Lifo queue forced to use the stack interface .You cannot arbitrarily insert values into the wrong place in the Lifo queue.
from queue import LifoQueue
_# Create object _
lifoQueue = LifoQueue()
(1)
(2)
(3)
print()
_# Returns and removes the trailing element of the queue.
print(())
print()
The results of the run are as follows:
Priority Queue
Priority queues force a very different sorting style than previous queue implementations. They still use the same get() and put() functions.The difference, however, is that they are not returned in the order in which they were added, but rather the "most important" elements are returned first. By convention, the most important, or highest-priority, element is the one ranked lowest by the less-than operation.
This is usually done by storing a tuple into a priority queue, where the first element of the tuple represents its priority and the second element is the data; another common paradigm is to implement the __lt__ method (there's no guarantee which one will be returned first when more than one element in the queue has the same priority).
Priority queues are useful in many real-world applications, such as task scheduling, network traffic control, and some algorithms in machine learning. Taking task scheduling as an example, a priority queue can be used to manage a set of tasks. Each task has a priority value, and the task with the highest priority value is executed first. By using a priority queue, you can ensure that high-priority tasks are processed in a timely manner.
If the queue is empty, the get() method will block (by default); if the queue is non-empty, it won't block and won't wait for higher-priority elements to be added.The queue doesn't care about elements that haven't been added yet (or even elements that have already been extracted) and makes decisions based solely on the current contents of the queue.
import queue
_# Create a priority queue _
q = ()
_# Put a tuple in the format (priority, data)_
_# The smaller the number, the higher the priority _#
((4,'aaaaa'))
((3,'bbbbb'))
((2,'ccccc'))
((1,'ddddd'))
print(())
print(())
print(())
print(())
The following is the result of the run:
Generic implementations of priority queues are based on the heap data structure, and the Python implementation utilizes the heapq module to efficiently store heaps in an unusual list. The heap heap is described in more detail later.
double-ended queue
Double-ended queue Double-ended queue, abbreviated as Deque, has the same name but not the same meaning as the queue operation out of a queue. In computer science, a double-ended queue (abbreviated deque) is an abstract data type that generalizes a queue in which elements can be added or deleted from the front (head) or back (tail). It is therefore also often referred to as a head-to-tail chained table.
There are two types of double-ended queues:
(1) Input-restricted double-ended queue:Inputs in this type of queue are restricted to one end, while deletions can occur at both ends simultaneously;
(2) Output-restricted double-ended queue:This type of queue can only perform deletions at one end, while inserting elements can be done at both ends.
Double-ended queues have a wide range of uses in many practical applications, some of which include:
- **Page caching: **Forward and backward functionality of the browser can be realized with a double-ended queue;
- Scheduling Algorithm. In some scheduling algorithms, double-ended queues can be used for priority scheduling of tasks;
- **Priority Queue: **The double-ended queue can be used as the base data structure for a priority queue.
The following is sample code for operations related to double-ended queues. First, we need to import the collections module, which implements a number of specialized containers that complement Python's general-purpose built-in containers dict, list, set, and tuple:
from collections import deque
_# Create a double-ended queue _
deque_obj = deque()
_# Insert an element in the head _
deque_obj.appendleft(10)
deque_obj.appendleft(15)
deque_obj.appendleft(20)
_# Insert the element _ at the end
deque_obj.append(25)
deque_obj.append(30)
print(deque_obj)
_# Loop right 2 times _
deque_obj.rotate(2)
print(deque_obj)
_# Remove element from head _
front = deque_obj.popleft()
print(front)
_# Remove element from tail_
rear = deque_obj.pop()
print(rear)
print(deque_obj)
The following are the results of the run:
circular queue
In a normal queue, once a queue is full, we can not insert the next element, even if there is still space in front of the queue. At this point, we can use the circular queue to realize the use of this queue before the space used, through the circular queue we can use this space to store new values. A circular queue is a linear data structure whose behavior is based on the FIFO (First In First Out) principle and whose tail is attached to the head of the queue to form a loop. It is also known as a "ring buffer".
A circular queue can logically be thought of as a ring, where the pointer to the head of the queue is equal to the length of the queue, minus one unit, and then advances one position to 0, which is the remainder operation. You can implement a circular queue using deque from Python's collections module. When you create a deque, you can specify a maximum length (maxlen=x), and if maxlen is unspecified or None, the deque can grow to any length. Otherwise, the deque is limited to the specified maximum length, and when the deque is full and new items are added, the same number of items will be popped from the other end. The example code is as follows:
from collections import deque
# Create a circular queue of size 3
queue = deque(maxlen=3)
# Add the elements
('a')
('b')
('c')
# Adding a fourth element causes the first element to be ejected
('d')
print(queue)
The following is the result of the run: