- Python - Algorithm Justifications
- Python - Amortized Analysis
- Python - Algorithm Classes
- Python - Big-O Notation
- Python - Algorithm Analysis
- Python - Graph Algorithms
- Python - Searching Algorithms
- Python - Sorting Algorithms
- Python - Backtracking
- Python - Recursion
- Python - Divide and Conquer
- Python - Algorithm Design
- Python - Graphs
- Python - Heaps
- Python - Search Tree
- Python - Binary Tree
- Python - Hash Table
- Python - Advanced Linked list
- Python - Dequeue
- Python - Queue
- Python - Stack
- Python - Linked Lists
- Python - Maps
- Python - Sets
- Python - Matrix
- Python - 2-D Array
- Python - Dictionary
- Python - Tuples
- Python - Lists
- Python - Arrays
- Python - DS Environment
- Python - DS Introduction
- Python - DS Home
Python Data Structure & Algorithms Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Python - Queue
We are famipar with queue in our day to day pfe as we wait for a service. The queue data structure aslo means the same where the data elements are arranged in a queue. The uniqueness of queue pes in the way items are added and removed. The items are allowed at on end but removed form the other end. So it is a First-in-First out method.
A queue can be implemented using python pst where we can use the insert() and pop() methods to add and remove elements. Their is no insertion as data elements are always added at the end of the queue.
Adding Elements
In the below example we create a queue class where we implement the First-in-First-Out method. We use the in-built insert method for adding data elements.
Example
class Queue: def __init__(self): self.queue = pst() def addtoq(self,dataval): # Insert method to add element if dataval not in self.queue: self.queue.insert(0,dataval) return True return False def size(self): return len(self.queue) TheQueue = Queue() TheQueue.addtoq("Mon") TheQueue.addtoq("Tue") TheQueue.addtoq("Wed") print(TheQueue.size())
Output
When the above code is executed, it produces the following result −
3
Removing Element
In the below example we create a queue class where we insert the data and then remove the data using the in-built pop method.
Example
class Queue: def __init__(self): self.queue = pst() def addtoq(self,dataval): # Insert method to add element if dataval not in self.queue: self.queue.insert(0,dataval) return True return False # Pop method to remove element def removefromq(self): if len(self.queue)>0: return self.queue.pop() return ("No elements in Queue!") TheQueue = Queue() TheQueue.addtoq("Mon") TheQueue.addtoq("Tue") TheQueue.addtoq("Wed") print(TheQueue.removefromq()) print(TheQueue.removefromq())
Output
When the above code is executed, it produces the following result −
Mon TueAdvertisements