1

I created a queue and i need to check whether a given element is inside that queue or not and to run the program according to that! Following is my code and it doesn't do what i want and it gives as "duplicate" for all inputs! Please help!

def Arrival(vehicle):

    if vehicle in q1.items:
        print "duplicate!"

    else:

        if q1.size()<10:
            if q3.isEmpty()==False:
                EnterOld=q3.dequeue()
                q1.enqueue(EnterOld)
                print "The car number "+str(EnterOld)+" can enter now from the waiting line!"
        else:
            print"the car number "+str(vehicle)+" can enter the park!"
Tharushi Geethma
  • 1,249
  • 15
  • 21
  • 3
    http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values – Eric Levieil May 18 '15 at 16:18
  • I don't fully understand what you're trying to do. What is `q1`, `q3`? What I understand so far, `q1` is the car park, `q3` is the line for the car park? Arrival then lets the first car enter? – Jorick Spitzen May 18 '15 at 16:46

4 Answers4

1

The problem is in your if statement.

if vehicle in q1.items or q3.items:

What this does is check 'is vehicle an element of q1.items', if not it checks 'is q3.items' True when evaluated as a boolean?

You should do:

if vehicle in q1.items or vehicle in q3.items:
Jorick Spitzen
  • 1,559
  • 1
  • 13
  • 25
0

I understand that the vehicle is duplicate if it is in both q1 and q3, so this should be

if vehicle in q1.items and vehicle in q3.items:

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

def __iter__(self):
    for i in self.items:
        yield i

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

def enqueue(self,item):
    self.items.insert(0,item)

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

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

def front(self):
    return self.items[len(self.items)-1]

def index(self,item):
    return self.items.index(item)
Tharushi Geethma
  • 1,249
  • 15
  • 21
  • 1
    Although this helped me, code-only answers aren't an acceptable level of quality. Please use complete sentences to describe this code and completely answer the question that was asked for the benefit of future readers. – Michael Fulton Nov 04 '18 at 22:02
0

This is my code. Hopefully, it can help someone.

I added set as a cache to the Queue class. This cache was utilized for task uniqueness checking. Moreover, it was used to implement the __contains__ magic method in the Queue class.

Uniqueness can be defined in two ways. First, tasks are unique in the whole life of the queue. In other words, the queue rejects accepting a repeated task even after the task is done and removed from the queue. I implemented this as "be_unique_in_all_items". Second, tasks are unique only in the existing tasks in the queue. It means the task can be accepted after it is done. I implemented this as "be_unique_in_existing_items".

from queue import Queue
from traceback import print_exc


class MQueue(Queue):

    def __init__(self,
                 **kwargs):
        super().__init__(maxsize=kwargs.get("maxsize", 0))

        self._be_unique_in_existing_items = kwargs.get("be_unique_in_existing_items", False)
        self._be_unique_in_all_items = kwargs.get("be_unique_in_all_items", False)

        if self._be_unique_in_existing_items and self._be_unique_in_all_items:
            raise ValueError("Choose one criteria")

        self.cache = set()

    def get(self, *args, **kwargs):
        result = super().get(*args, **kwargs)

        if result:
            if self._be_unique_in_existing_items:
                self.cache.remove(result)

        return result

    def put(self, item, *args, **kwargs):
        if self._be_unique_in_existing_items or self._be_unique_in_all_items:
            if item in self.cache:
                raise ValueError("The given item exists in cache.")
            self.cache.add(item)

        return super().put(item, *args, **kwargs)

    def __contains__(self, item):
        if self._be_unique_in_existing_items or self._be_unique_in_all_items:
            return self.cache.__contains__(item)
        else:
            return Queue.__contains__(item)  # will raise you error


if __name__ == "__main__":
    # ordinary queue
    ordinary_queue_obj = MQueue(maxsize=0)

    ordinary_queue_obj.put(1)
    ordinary_queue_obj.put(1)

    try:
        print(1 in ordinary_queue_obj)
    except Exception:
        print_exc()

    # be unique in existing queue
    unique_in_existing_queue_obj = MQueue(maxsize=0,
                                          be_unique_in_existing_items=True)

    unique_in_existing_queue_obj.put(1)

    print(1 in unique_in_existing_queue_obj)

    try:
        unique_in_existing_queue_obj.put(1)
    except ValueError:
        print_exc()

    task = unique_in_existing_queue_obj.get()
    unique_in_existing_queue_obj.task_done()
    unique_in_existing_queue_obj.put(task)

    # be unique in all queue
    unique_in_all_queue_obj = MQueue(maxsize=0,
                                     be_unique_in_all_items=True)

    unique_in_all_queue_obj.put(1)
    print(1 in unique_in_all_queue_obj)

    try:
        unique_in_all_queue_obj.put(1)
    except ValueError:
        print_exc()

    task = unique_in_all_queue_obj.get()
    unique_in_all_queue_obj.task_done()
    try:
        print(task in unique_in_all_queue_obj)
        unique_in_all_queue_obj.put(task)
    except ValueError:
        print_exc()

Note: set only can contain hashable objects. For unhashable objects use list instead.

r_agha_m
  • 310
  • 3
  • 6