Answers for "queue methods python"

2

python get item from queue

"""put and get items from queue"""
>>> from Queue import Queue
>>> q = Queue()
>>> q.put(1)
>>> q.put(2)
>>> q.put(3)
>>> print list(q.queue)
[1, 2, 3]

>>> q.get()
1
>>> print list(q.queue)
[2, 3]
Posted by: Guest on April-04-2020
1

python threading queue

import threading, queue

q = queue.Queue()

def worker():
    while True:
        item = q.get()
        print(f'Working on {item}')
        print(f'Finished {item}')
        q.task_done()

# turn-on the worker thread
threading.Thread(target=worker, daemon=True).start()

# send thirty task requests to the worker
for item in range(30):
    q.put(item)
print('All task requests sentn', end='')

# block until all tasks are done
q.join()
print('All work completed')
Posted by: Guest on October-29-2020
4

python queue.priority queue

from queue import PriorityQueue

class PqElement(object):
    def __init__(self, value: int):
        self.val = value

    #Custom Compare Function (less than or equsal)
    def __lt__(self, other):
        """self < obj."""
        return self.val > other.val

    #Print each element function
    def __repr__(self):
        return f'PQE:{self.val}'

#Usage-
pq = PriorityQueue()
pq.put(PqElement(v))       #Add Item      - O(Log(n))
topValue = pq.get()        #Pop top item  - O(1)
topValue = pq.queue[0].val #Get top value - O(1)
Posted by: Guest on November-01-2020
0

queue in python

#creating a queue using list

#defining a list

my_queue =[]

#inserting the items in the queue

my_queue.append(1)

my_queue.append(2)

my_queue.append(3)

my_queue.append(4)

my_queue.append(5)

print("The items in queue:")

print(my_queue)

#removing items from queue

print(my_queue.pop(0))

print(my_queue.pop(0))

print(my_queue.pop(0))

print(my_queue.pop(0))

#printing the queue after removing the elements

print("The items in queue:")

print(my_queue)
Posted by: Guest on March-21-2021

Python Answers by Framework

Browse Popular Code Answers by Language