Skip to content

Commit 80a39f1

Browse files
Animal Shelter
1 parent 777e44e commit 80a39f1

File tree

1 file changed

+88
-0
lines changed
  • Python/chapter03/3.6 - Animal Shelter

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
#!/usr/bin/python3
2+
'''Animal Shelter: An animal shelter, which holds only
3+
dogs and cats, operates on a strictly"first in, first
4+
out" basis. People must adopt either the "oldest"
5+
(based on arrival time) of all animals at the shelter,
6+
or they can select whether they would prefer a dog or
7+
a cat (and will receive the oldest animal of that type).
8+
They cannot select which specific animal they would
9+
like. Create the data structures to maintain this
10+
system and implement operations such as enqueue,
11+
dequeueAny, dequeueDog, and dequeueCat. You may use
12+
the built-in Linked list data structure.
13+
Hints: #22, #56, #63'''
14+
import unittest
15+
16+
17+
class ShelterQueue:
18+
def __init__(self):
19+
self.queue = []
20+
21+
def enqueue(self, animal):
22+
if len(self.queue) == 0:
23+
self.queue.append(animal)
24+
else:
25+
self.queue.insert(0, animal)
26+
27+
def printQueue(self):
28+
print('----- Beginning of Queue ------')
29+
for x in self.queue[::-1]:
30+
print(x)
31+
print('------ End of Queue ------')
32+
33+
def dequeueAnimal(self, animal):
34+
if len(self.queue) == 0:
35+
return
36+
temp = False
37+
for x in self.queue[::-1]:
38+
if animal in x:
39+
temp = x
40+
break
41+
if temp:
42+
pet = temp
43+
self.queue.remove(temp)
44+
return pet
45+
46+
def dequeueDog(self):
47+
return self.dequeueAnimal('D')
48+
49+
def dequeueCat(self):
50+
return self.dequeueAnimal('C')
51+
52+
def dequeueAny(self):
53+
if len(self.queue) == 0:
54+
return
55+
return self.queue.pop()
56+
57+
58+
class Test(unittest.TestCase):
59+
@classmethod
60+
def setUpClass(cls):
61+
q = ShelterQueue()
62+
animals = ['D1', 'D2', 'C1', 'D3', 'C2', 'C3', 'C4']
63+
for x in animals:
64+
q.enqueue(x)
65+
66+
q.printQueue()
67+
print('{} got adopted!'.format(q.dequeueDog())) # D1
68+
print('{} got adopted!'.format(q.dequeueCat())) # C1
69+
q.printQueue()
70+
71+
print('{} got adopted!'.format(q.dequeueAny())) # D2
72+
print('{} got adopted!'.format(q.dequeueCat())) # C2
73+
print('{} got adopted!'.format(q.dequeueAny())) # D3
74+
print('{} got adopted!'.format(q.dequeueDog())) # No Dogs
75+
print('{} got adopted!'.format(q.dequeueAny())) # C3
76+
print('{} got adopted!'.format(q.dequeueCat())) # C4
77+
print('{} got adopted!'.format(q.dequeueCat())) # No Cats
78+
79+
@classmethod
80+
def tearDownClass(cls):
81+
pass
82+
83+
def test1(self):
84+
pass
85+
86+
87+
if __name__ == '__main__':
88+
unittest.main()

0 commit comments

Comments
 (0)