Data Structure and algorithm queue details implemented by Python, python data structure and Algorithm
This article describes the data structure and algorithm queue implemented by Python. Share it with you for your reference. The specific analysis is as follows:
I. Overview
A Queue is a first-in-first-out (FIFO) linear data structure. The insert operation is performed at the end of the Queue (rear), and the delete operation is performed at the front of the Queue.
Ii. ADT
The queue ADT (abstract data type) generally provides the following interfaces:
① Queue () creates a Queue
② Enqueue (item) inserts an item to the end of the team
③ Dequeue () returns the first item of the queue and deletes the item from the queue.
④ Empty () determines whether the queue is empty
⑤ Size () returns the number of items in the queue
Queue operations are as follows:
Iii. Python implementation
Using Python's built-in list, you can easily implement the 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 Joseph's Problem is a typical case of application queues (specifically, cyclic queues. In the Joseph's question, participants form a circle and report the number from a person (first of the Team). The number of people who report the number to n + 1 exit the circle, then, report the number again from the next digit of the exited person. Repeat the above actions until only one person is left.
It is worth noting that the Queue class only implements simple queues, and the above problems need to be solved using cyclic queues. During the reporting process, the behaviors of the cyclic queue are simulated by "adding (starting from the front of the team) to the back of the Team (to the end of the Team. The 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: 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))
Running result:
$ python josephus.pySusan
I hope this article will help you with Python programming.