nce. write a class i ntOueue that stores a queue of i nt·s. A queue ems on one e
ID: 3667155 • Letter: N
Question
nce. write a class i ntOueue that stores a queue of i nt·s. A queue ems on one end and removes/dequeues from the other. You MUST om list. Errors will result if any code attempts to enqueue anything 2. Container/ tainer/Inheritance. Writ ueues it inherit/subclass from 1 other than an intQueue. int, or, if code attempts to assign to a location in the middle of the An intQueue can be constructed with a given list, if none is given it defaults to the em list: >>>intQueue) intQueue ([1) >>> intQueue (13,4,51) intQueue[[3, 4, 5)) The method enqueue adds to the back, dequeue removes from the front and returns the item qintQueue (15,61) >>> q.enqueue (7) >>>q.enqueue (8) intQueue (I5, 6, 7, 8]) >>> q.dequeue )--5 True >>> q.dequeue )--6 True intQueue ((7, 81) Any attempt to add anything but an int raises an error. This can happen in enqueue or the constructor >>>iq intQueue ) >>>iq.enqueue ( 5.5 Traceback (most recent call last): NotIntError: 5.5 is not an int >>> iq.enqueue( 'hello' Traceback (most recent call last): NotIntError: hello is not an int >>>iq.enqueue( [) Traceback (most recent call last): NotIntError: [ is not an int >>> intQueue ( 13, 4 . 55,5)) Traceback (most recent cal1 last): NotIntError: 4.55 is not an int ...continues on next page...Explanation / Answer
class intQueue(list):
q = []
def __init__(self, l = []):
try:
for i in l:
if type(i) != int:
raise NotIntError(i)
except NotIntError, i:
pass
else:
self.q = l
def enqueue(self, e):
if type(i) != int:
raise NotIntError(i)
q.append(e)
def dequeue(self):
x = self.q[0]
del self.q[0]
return x
def __repr__(self):
p = ', '.join(str(x) for x in self.q)
return 'intQueue(' + p + ')'
def __getitem__(self, i):
return self.q[i]
def __setitem__(self, i, v):
try:
raise CuttingError(i)
except CuttingError, i:
pass
class NotIntError(Exception):
def __init__(self, i):
print 'NotIntError: ' + str(i) + ' is not an integer'
class CuttingError(Exception):
def __init__(self, i):
print 'CuttingError: no cutting'
oo = intQueue([1, 2])
print oo
oo[0] = 77
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.