This article mainly introduces the definition and use of queues in Python. It analyzes the definition and use of queues in Python based on specific examples and the specific operating techniques and precautions required. Friends can refer to
The examples in this article describe the definition and use of Python queues. Share it with everyone for your reference, the details are as follows:
Although Python has its own queue module, we only need to introduce the module when using it, but in order to better understand the queue, we implemented the queue ourselves.
Queue is a data structure, which is characterized by first-in, first-out, which means that an element is added to the end of the queue and an element is removed from the head of the queue. It is similar to queuing up for checkout at a shopping mall. The person who comes first takes the bill first. , and those who came later were at the end of the queue. In our daily life, queues are used when sending text messages. The following is the code to implement the queue in Python:
#!/usr/bin/python #coding=utf-8 class Queue(object) : def init(self, size) : self.size = size self.queue = [] def str(self) : return str(self.queue) #获取队列的当前长度 def getSize(self) : return len(self.quene) #入队,如果队列满了返回-1或抛出异常,否则将元素插入队列尾 def enqueue(self, items) : if self.isfull() : return -1 #raise Exception("Queue is full") self.queue.append(items) #出队,如果队列空了返回-1或抛出异常,否则返回队列头元素并将其从队列中移除 def dequeue(self) : if self.isempty() : return -1 #raise Exception("Queue is empty") firstElement = self.queue[0] self.queue.remove(firstElement) return firstElement #判断队列满 def isfull(self) : if len(self.queue) == self.size : return True return False #判断队列空 def isempty(self) : if len(self.queue) == 0 : return True return False
The following is the test code for the queue class .py file:
if name == 'main' : queueTest = Queue(10) for i in range(10) : queueTest.enqueue(i) print queueTest.isfull() print queueTest print queueTest.getSize() for i in range(5) : print queueTest.dequeue() print queueTest.isempty() print queueTest print queueTest.getSize()
Test Results:
The above is the detailed content of Detailed explanation of the definition and usage of Python queues with examples. For more information, please follow other related articles on the PHP Chinese website!