Home > Back-end >  Can anyone tell me what's wrong with my dequeue function, it wont remove anything from the queu
Can anyone tell me what's wrong with my dequeue function, it wont remove anything from the queu

Time:09-17

Implementing a queue using imperative programming, i tried introducing a dequeue function but it's not working, Check for errors please .

queue = [None for index in range(0, 10)]

rearPointer = -1
frontPointer = 0
queueFull = 10
queueLength = 0

def Dequeue():
    global queueLength, frontPointer, Item
    if queueLength == 0:
        print("Queue is empty, cannot dequeue")
    else:
        #item = queue[frontPointer]
        if frontPointer == (len(queue) - 1):
            frontPointer = 0
        else:
            frontPointer  = 1
    queueLength -= 1

CodePudding user response:

I think it makes no sense to implement this when already exist a deque object. except just as an excersise.

from collections import deque

queue = [index for index in range(0, 10)]
my_deque = deque(queue)

Now you can use popleft and pop to dequeue

print(queue)
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for _ in range(3):
    out = my_deque.popleft()
    print(out)
>>>
0
1
2

for _ in range(3):
    out = my_deque.pop()
    print(out)
>>>
9
8
7

If you want to implement this yourself Sparkling Marcel is correct, his answer is giving you everything you need. Your functions should look like this:

def Dequeueleft(queue, number=1):
    if len(queue) == 0:
        print("Queue is empty, cannot dequeue")
    values = []
    for _ in range(number):
        val = queue[0]
        queue = queue[1:]
        values.append(val)
    return queue, values

# equivalent fucntion
def Dequeueleft(queue, number=1):
    if len(queue) == 0:
        print("Queue is empty, cannot dequeue")
    values = [val for val in queue[:number]]
    return queue[number:], values

output

queue = [index for index in range(0, 10)]
queue, vals = Dequeueleft(queue, 2)
print(queue, vals)
>>> [2, 3, 4, 5, 6, 7, 8, 9] [0, 1]

CodePudding user response:

You're actually never removing any item from your list in your dequeue function, ence why it does nothing

All you're really doing right now is changing queueLength and frontPointer value, but never touching queue itself

What you would want to do is simply removing the first element of your list (aka queue)

And then move every item one place before, so the earlier 2nd element becomes first

  • Related