In this paper, we describe the data structure and algorithm of Python. Share to everyone for your reference. The specific analysis is as follows:
I. Overview
A queue is a first-in (FIFO) linear data structure that is inserted at the end of the team (rear), and the delete operation is performed at the head of the team (front).
Second, ADT
Queue ADT (abstract data type) generally provides the following interfaces:
①queue () Create queue
②enqueue (item) Inserts an item to the end of the queue
③dequeue () returns the entry for the first team and removes the item from the queue
④empty () Determine if the queue is empty
⑤size () returns the number of items in the queue
The queue operations are as follows:
Third, Python implementation
Using Python's built-in type list lists makes it easy to 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)
Iv. Application
The famous Josephus problem (Josephus problem) is a typical case of the application queue (or, to be exact, a cyclic queue). In the Josephus problem, the participants in a circle, from a person (team head) began to count, count to n+1 people exit the circle, and then from the exit of the next one to restart the count; Repeat the above action until there is only one person left.
It is worth noting that the queue class only implements a simple queue, and the above problem actually needs to be solved with a circular queue. In the process of count off, through the "Will (from the team first) out of the team to the queue (to the end of the team)" to simulate the behavior of cyclic queues. The specific code is as follows:
#!/usr/bin/env python#-*-coding:utf-8-*-def Josephus (NameList, num): simqueue = Queue () for name in namelist:< C2/>simqueue.enqueue (name) while simqueue.size () > 1: For 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))
Operation Result:
$ python Josephus.pysusan
Hopefully this article will help you with Python programming.