class AnimalShelter(): q = None # Queue def __init__(self): # create internal data structs self.q = Queue() def enqueue(self, animal: Animal): # add animal to shelter self.q.enqueue(animal.serialize()) def dequeue(self, pref: AnimalType = None) -> Animal: # grab animal that has been in queue the longest, optionally provide parameter # No Pref First if pref == None: b, val = self.q.peek() if not b: return None if self.q.dequeue(val): return Animal.Factory(val) else: stack = Stack() # Find the Animal we Want (deq, push to stack) found = False b, val = self.q.peek() while b: animal = Animal.Factory(val) if animal.animaltype == pref: found = True break stack.push(val) self.q.dequeue(val) b, val = self.q.peek() if found: # Pop off stack and enqueue back to queue # record the current count, as we need to cycle the enq (back of line) to the front c = self.q.count() b, val = stack.peek() while b: val = stack.pop() self.q.enqueue(val) b, val = stack.peek() # cycle the back of the list to the front diff = self.q.count() - c for x in range(diff): val = self.q.peek() self.q.dequeue(val) self.q.enqueue(val) return animal else: return None
def test_queue_enqueue(): # enqueue into a queue q = Queue() q.enqueue('pao de queijo') assert q.count() == 1