1,add方法将Dog实例或Cat实例加入猫狗队列
2,pollAll将猫狗队列中的实例按插入顺序弹出
3,pollDog将猫狗队列中的Dog实例按插入顺序弹出
4,pollCat将猫狗队列中的Cat实例按插入顺序弹出
5,isEmpty判断猫狗队列中是否还有实例
6,isDogEmpty判断猫狗队列中是否还有Dog实例
7,isCatEmpty判断猫狗队列中是否还有Cat实例
#!/usr/bin/env python3 # --*-- coding: utf-8 --*-- from collections import deque class Pet: count = 0 def __init__(self): pass def __str__(self): Pet.count += 1 return ‘Pet {}‘.format(Pet.count) class Dog(Pet): count = 0 def __init__(self): pass def __str__(self): Dog.count += 1 return ‘Dog {}‘.format(Dog.count) class Cat(Pet): count = 0 def __init__(self): pass def __str__(self): Cat.count += 1 return ‘Cat {}‘.format(Cat.count) class CountedPet: count = 0 def __init__(self, pet): CountedPet.count += 1 self.pet = pet self.index = CountedPet.count class CatDogQueue: catque = deque() dogque = deque() def add(self, pet): countedPet = CountedPet(pet) self.catque.append(countedPet) if isinstance(pet, Cat) else self.dogque.append(countedPet) def pollAll(self): if self.catque or self.dogque: if not self.dogque: return self.catque.popleft().pet elif not self.catque: return self.dogque.popleft().pet else: return self.dogque.popleft().pet if self.dogque[0].index < self.catque[0].index else self.catque.popleft().pet def pollCat(self): if self.catque: return self.catque.popleft().pet def pollDog(self): if self.dogque: return self.dogque.popleft().pet def isEmpty(self): return False if self.catque or self.dogque else True def isDogEmpty(self): return False if self.dogque else True def isCatEmpty(self): return False if self.catque else True if __name__ == ‘__main__‘: ‘‘‘test here‘‘‘
时间: 2024-10-21 16:36:44