This article describes the data structure of Python implementation and the queue of algorithms. Share to everyone for your reference. The specific analysis is as follows:
 
I. Overview
 
Queues (queue) is a first-in, first-out (FIFO) linear data structure in which the insertion operation is performed at the end of the team (rear), and the deletion is performed at the head of the team (front).
 
Second, ADT
 
The queue ADT (abstract data type) generally provides the following interfaces:
 
①queue () Create queues
②enqueue (item) Inserts an item to the end of the team
③dequeue () returns the entry for the first team and deletes the item from the queue
④empty () to determine whether the queue is empty
⑤size () returns the number of items in the queue
 
The sketch of the queue operation is as follows:
 
 
Three, Python implementation
 
With Python's built-in type list, you can easily implement queue ADT:
 
 
  
  
#!/usr/bin/env python
#-*-coding:utf-8-*-
class Queue:
  def __init__ (self):
    self.items = []
  def Enqueue (self, item):
    self.items.append (item)
  def dequeue (self): return
    self.items.pop (0)
  def Empty (self): return
    self.size () = = 0
  def size (self): return
    len (self.items) 
   
  
Four, the application
 
The famous Josephus problem (Josephus Problem) is a typical case of application queues (specifically, circular queues). In the Josephus question, the participant circles in a circle, from a person (team head) starts to count off, count to the n+1 person to exit the circle, then from the exit person's next to start to count again; Repeat the above action until only one person is left.
 
It is worth noting that the queue class only implements a simple queue, and the above problems actually need to be solved with a circular queue. In the course of the count, the behavior of the loop queue is simulated by "putting the team (from the head of the team) back into the team (to the end)". The specific code is as follows:
 
 
  
  
#!/usr/bin/env python
#-*-coding:utf-8-*-
def Josephus (NameList, num):
  simqueue = Queue () for
  name in NameList:
    simqueue.enqueue (name) while
  simqueue.size () > 1: To
    i in xrange (num):
      Simqueue.enqueue (Simqueue.dequeue ())
    Simqueue.dequeue () return
  simqueue.dequeue ()
if __name__ = = ' __ main__ ':
  print (Josephus (["Bill", "David", "Kent", "Jane", "Susan", "Brad"], 3)) 
   
  
Run Result:
 
 
  
  
$ python josephus.py
Susan
 
   
  
I hope this article will help you with your Python programming.