I am trying make a function that takes a number as a parameter and removes all occurrences of it from a Queue

class Queue:
    def __init__(self):
        self.items = []

    def is_empty(self):
        return self.items == []

    def add(self, item):

    def remove(self):
        return self.items.pop()

I need to create a function that takes in a number as a parameter and a queue then removes every occurrence of that number in the queue but with the exception of the omissions. I've put up a model of what my Queue looks like above and I'll put a model of what the queue should somewhat look like (It's very messy and in its early stages) below.

def remove_item(q, val):
q_temp = Queue

while not q.is_empty():

I cannot directly modify it in any way and I can't put the elements of the Queue in a normal list. Anyone got any solutions?

Edit: Also it needs to be executable in IDLE like this


2 answers

  • answered 2017-06-17 18:00 moritzg

    What I would do is something like this:

    number_to_remove = 123 
    for i in range(0, queue.length()):
        number = queue.remove()
        if number != number_to_remove:

    That way you "loop" trough the queue, you look at every number and if it's not the number you should remove then just add it again. You need to create the .length() method though.

  • answered 2017-06-17 18:00 Iván C.

    That code will fail because bad indentation:

    def remove_item(q, val):
    #>  q_temp = Queue

    And you're setting q_temp to the class, not to an instance, making that it can't be modified.

        q_temp = Queue()

    And, the .remove method doesn't work, there's an easier way to make it work:

    def remove(self):
        return self.items.pop(-1)

    But I don't have a (fully valid) answer. I we could get the queue's items, I'd use conditional list comprehensions for deleting determinated items, and applying that into the queue.

    def removeFromQueue(queue, value = ""):
        items = queue.items
        queue.items = [i for i in items if i != value]
        return queue

    You can do if you let us to use the Queue class use only the class methods (we can make variables, make another queues, .remove and .add numbers, but not to use .items) you can do this:

    def removeFromQueue(queue, value = ""):
      items = []
      for i in len(queue):
      items = [i for i in items if i != value]:
      for i in items:

    I don't think that's valid, though. And it would need defining Queue.__len__()*:

    def __len__(self):
        return len(self.items)

    * or modififying the code and defining __iter__ or some sort of thing like that