- Exception Handling
- Python Design Patterns - Anti
- Concurrency in Python
- Strings & Serialization
- Python Design Patterns - Queues
- Python Design Patterns - Sets
- Lists Data Structure
- Dictionaries
- Python Design Patterns - Iterator
- Object Oriented Concepts Implementation
- Object Oriented
- Abstract Factory
- Python Design Patterns - Flyweight
- Python Design Patterns - Template
- Python Design Patterns - Strategy
- Python Design Patterns - State
- Python Design Patterns - Observer
- Chain of Responsibility Pattern
- Python Design Patterns - Proxy
- Python Design Patterns - Decorator
- Python Design Patterns - Adapter
- Python Design Patterns - Command
- Python Design Patterns - Facade
- Python Design Patterns - Prototype
- Python Design Patterns - Builder
- Python Design Patterns - Factory
- Python Design Patterns - Singleton
- Model View Controller Pattern
- Python Design Patterns - Gist
- Introduction
- Python Design Patterns - Home
Python Design Patterns Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Python Design Patterns - Queues
Queue is a collection of objects, which define a simple data structure following the FIFO (Fast In Fast Out) and the LIFO (Last In First Out) procedures. The insert and delete operations are referred as enqueue and dequeue operations.
Queues do not allow random access to the objects they contain.
How to implement the FIFO procedure?
The following program helps in the implementation of FIFO −
import Queue q = Queue.Queue() #put items at the end of the queue for x in range(4): q.put("item-" + str(x)) #remove items from the head of the queue while not q.empty(): print q.get()
Output
The above program generates the following output −
How to implement the LIFO procedure?
The following program helps in the implementation of the LIFO procedure −
import Queue q = Queue.LifoQueue() #add items at the head of the queue for x in range(4): q.put("item-" + str(x)) #remove items from the head of the queue while not q.empty(): print q.get()
Output
The above program generates the following output −
What is a Priority Queue?
Priority queue is a container data structure that manages a set of records with the ordered keys to provide quick access to the record with smallest or largest key in specified data structure.
How to implement a priority queue?
The implementation of priority queue is as follows −
import Queue class Task(object): def __init__(self, priority, name): self.priority = priority self.name = name def __cmp__(self, other): return cmp(self.priority, other.priority) q = Queue.PriorityQueue() q.put( Task(100, a not agent task ) ) q.put( Task(5, a highly agent task ) ) q.put( Task(10, an important task ) ) while not q.empty(): cur_task = q.get() print process task: , cur_task.name
Output
The above program generates the following output −
Advertisements