Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

rotating circular queue in python

def circularArrayRotation(a, k, queries):
    from collections import deque 
    items = deque(a) 
    items.rotate(k)
    ret_list = []
    for q in queries:
        #print(items[q])
        ret_list.append(items[q])
    return ret_list
Comment

circular 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

PREVIOUS NEXT
Code Example
Python :: how to check if number has decimals python 
Python :: remove prefix from string python 
Python :: clone keras model 
Python :: tensorflow to numpy 
Python :: python save to excel 
Python :: socket exception python 
Python :: django pass parameters in url 
Python :: driver code in python 
Python :: depth first search python recursive 
Python :: mse python 
Python :: remove unnamed columns pandas 
Python :: Get current cursor type and color Tkinter Python 
Python :: remove white border matplotlib 
Python :: xpath starts-with and ends-with 
Python :: lastindexof python 
Python :: letters to numbers python 
Python :: python matplotlib 
Python :: numpy diff 
Python :: load image metadata with pil 
Python :: AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’ 
Python :: python disable logging on unittest 
Python :: pandas hist normalized 
Python :: how to make a leaderboard in python 
Python :: Python Selenium import WebElement 
Python :: flask session timeout 
Python :: baeutifulsoup find element with text 
Python :: check if list is empty python 
Python :: start process python 
Python :: save model pytorch 
Python :: set and tuple in python 
ADD CONTENT
Topic
Content
Source link
Name
4+5 =