Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

queue python

from queue import Queue  # watch out with the capital letters

# Making the queue
queuename = Queue()

# We use .put() to insert value and .get() to pop the first one.
# You can think this as a normal queue

queuename.put(1)  # adds int 1 to index 0
# To access the queue, you need to change it to list
print(list(queuename.queue))
# Output : [1]

queuename.put(2)  # adds int 2 to index 1
print(list(queuename.queue))
# Output: [1,2]

queuename.get()  # removes index 0 (int 1)
print(list(queuename.queue))
# Output: [2]

# We can simulate the same effects using normal list, but the longer the queue
# the more ineffecient it becomes

queuesimulate.append(1)
print(queuesimulate)
# Output : [1]

queuesimulate.append(2)
print(queuesimulate)
# Output: [1,2]

queuesimulate.pop(0)  # 0 is the index number
print(queuesimulate)
# Output: [2]
Comment

queue in python

import queue
 
q = queue.Queue # initialisation

# get() – Remove and return an item from the queue. If queue is empty, wait until an item is available.
# put(item) – Put an item into the queue. If the queue is full, wait until a free slot is available before adding the item.
# empty() – Return True if the queue is empty, False otherwise.  
# maxsize – Number of items allowed in the queue.
# full() – Return True if there are maxsize items in the queue. If the queue was initialized with maxsize=0 (the default), then full() never returns True.
# get_nowait() – Return an item if one is immediately available, else raise QueueEmpty.
# put_nowait(item) – Put an item into the queue without blocking. If no free slot is immediately available, raise QueueFull.
# qsize() – Return the number of items in the queue.
Comment

queue functions in python

# Python program to
# demonstrate implementation of
# queue using queue module
  
  
from queue import Queue
  
# Initializing a queue
q = Queue(maxsize = 3)
  
# qsize() give the maxsize 
# of the Queue 
print(q.qsize()) 
  
# Adding of element to queue
q.put('a')
q.put('b')
q.put('c')
  
# Return Boolean for Full 
# Queue 
print("
Full: ", q.full()) 
  
# Removing element from queue
print("
Elements dequeued from the queue")
print(q.get())
print(q.get())
print(q.get())
  
# Return Boolean for Empty 
# Queue 
print("
Empty: ", q.empty())
  
q.put(1)
print("
Empty: ", q.empty()) 
print("Full: ", q.full())
  
# This would result into Infinite 
# Loop as the Queue is empty. 
# print(q.get())
Comment

queue python

"""Linear Queue
Queue is a First In - First Out (FIFO) data structure much like a real queue
	- The below is a simple implementation of a Linear Queue

Check out the source for more info!
"""

class LQ:
    def __init__(self):
        self.q = []
    
    def enq(self, data): # enqueue
        self.q.append(data)
        
    def deq(self): #dequeue
        if self.q:
            return self.q.pop(0)
        return "Empty!"
    
    def peek(self):
        if self.q:
            return self.q[0]
        return "Empty!"
    
    def size(self):
        return len(self.q)
    
    def display(self):
        return self.q

# Test
from random import randrange
def LQ_Test(LQ):
    # Create random list
    lst = [randrange(10, 100) for _ in range(10)]
    print(f"List: {lst}")
    
    # Create Empty LQ
    LQ = LQ()
    print(f"LQ: {LQ.display()}",
          f"Size: {LQ.size()}",
          f"Front: {LQ.peek()}",
          sep = " | ", end = "

")
    
    # Put items into LQ
    for item in lst: 
        LQ.enq(item)
    print(f"Front: {LQ.peek()}",
          f"LQ: {LQ.display()}",
          sep = " | ", end = "

")
    
    # Remove items from LQ
    for _ in range(len(lst)): 
        print(f"Deq: {LQ.deq()}", 
              f"Front: {LQ.peek()}",
              f"Size: {LQ.size()}", 
              f"LQ: {LQ.display()}",
              sep = " | ")
LQ_tester(LQ)
Comment

queue class python

""" Circular Queue
1. Below is a class implementation

2. Essential features: 
      - [Enqueue] puts items into the list via (tail)
      - [Dequeue] removes items from the list via (head)
      - Wraparound using modulus sign to keep the index...
        ...within the range of the queue
    
3. This is an implementation that doesnt require head and tail to...
   ...have -1 as the default value for an empty list

This is my attempt at shortening the CircularQueue class
Check out the source for more info!
"""
class CircularQueue:
    def __init__(self, max_size, start=0):
        self._queue = [None]*max_size
        self._max_size = max_size
        self._size = 0
        self._head = self._tail = start
    
    def empty(self):
        return self._size == 0
    
    def full(self):
        return self._size == self._max_size
    
    def update_tail(self):
        self._tail = (self._tail + 1) % self._max_size
    
    def update_head(self):
        self._head = (self._head + 1) % self._max_size
        
    def enqueue(self, data): # enqueue
        if self.full():
            return "Full"

        # Put item into queue
        self._queue[self._tail] = data
        self._size += 1
        self.update_tail()
        
        # To check
        return data
    
    def dequeue(self): # dequeue
        if self.empty():
            return "Empty"
        
        # Remove item from queue
        data = self._queue[self._head]
        self._queue[self._head] = None
        self._size -= 1
        self.update_head()
        
        # To check
        return data
    
    def head_at(self):
        return self._head
    
    def tail_at(self):
        return self._tail
    
    def max_size_of(self):
        return self._max_size
    
    def size_of(self):
        return self._size
    
    def display(self):
        return self._queue
    
# Test 
from random import randrange
def CQ_Test(CQ):
    # Create random list
    lst = [randrange(10, 100) for _ in range(10)]
    print(f"List: {lst}", 
          sep = " | ", end = "

")
    
    # Create Empty CQ with length less than lst
    len_CQ = len(lst) - 1
    CQ = CQ(len_CQ)
    print(f"Enq:   ",
          f"used: {CQ.usedslots()}",
          f"H,T: {CQ.head_at()}, {CQ.tail_at()}",
          f"CQ: {CQ.display()}", 
          sep = " | ")   ## Display Empty CQ
    
    # Fill CQ completely
    for item in lst:
        print(f"Enq: {CQ.enq(item)}",
              f"used: {CQ.usedslots()}",
              f"H,T: {CQ.head_at()}, {CQ.tail_at()}",
              f"CQ: {CQ.display()}",
              sep = " | ")
    print()
    
    # Remove half of CQ
    mid = len_CQ // 2
    for i in range(mid):
        print(f"Deq: {CQ.deq()}", 
              f"used: {CQ.usedslots()}",
              f"H,T: {CQ.head_at()}, {CQ.tail_at()}", 
              f"CQ: {CQ.display()}",
              sep = " | ")
    print()
    
    # Fill CQ back to full
    for i in range(mid, len_CQ - 1):
        print(f"Enq: {CQ.enq(lst[i])}", 
              f"used: {CQ.usedslots()}",
              f"H,T: {CQ.head_at()}, {CQ.tail_at()}",
              f"CQ: {CQ.display()}",
              sep = " | ")
    print()    
    
    # Remove all in CQ
    for i in range(len_CQ + 1):
        print(f"Deq: {CQ.deq()}", 
              f"used: {CQ.usedslots()}",
              f"H,T: {CQ.head_at()}, {CQ.tail_at()}",
              f"CQ: {CQ.display()}",
              sep = " | ")
CQ_Test(CQ)

"""Latest Edits 
   
1. Removed: 
    def usedslots(self):
      return sum(_ is None for _ in self.q)

- The reason I removed the method size() is that it was not time efficient. 
- Instead, updating self.used at enq() and deq() is better.
- It could have just been self.q.count(None) instead lol
"""
Comment

queue in python

#1 Use normal list 
arr=[]
#for pushing in the end use arr.append() Method
# for popping from the first use arr.pop(0)

#2 Use deque
from collections import deque
#the initialize
queue=deque()
#for pushing use append Method
#for popping use queue.popleft()
Comment

PREVIOUS NEXT
Code Example
Python :: python while loop 
Python :: python decimal 
Python :: k-means clustering 
Python :: tuples vs list 
Python :: what is the ternary operator in python 
Python :: numpy array into tuple 
Python :: how to read a file in python 
Python :: python syntaxerror: unexpected character after line continuation character 
Python :: search object in array python 
Python :: how to make a letter capital in python 
Python :: how to convert decimal to binary 
Python :: Heroku gunicorn flask login is not working properly 
Python :: add user agent selenium python canary 
Python :: python program to calculate factorial of a number. 
Python :: print treelib.Tree 
Python :: quadrilateral 
Python :: how to change the starting number for the loop count in pythin 
Python :: check if string has square brackets python 
Python :: when to use python sets 
Python :: with suppress(exception) python 
Python :: restart device micropython 
Python :: showing typle results with for loop in py in one line 
Python :: write str in a formal way in python 
Python :: lib.stride_tricks.sliding_window_view(x, window_shape, axis=None, *, subok=False, writeable=False) 
Python :: fungsi untuk mengecek apakah ada data yang kosong 
Python :: python [a]*b means [a,a,...b times] 
Python :: Encapsulation in Python using public members 
Python :: yticks in plotly expres 
Python :: ORing two cv mat objects 
Python :: withdraw() opposite tjinter 
ADD CONTENT
Topic
Content
Source link
Name
6+1 =