Problem:Implement a queue class in Python: It should support 3 APIs:
queue.top(): prints current element at front of queue
queue.pop(): takes out an element from front of queue
queue.add(): adds a new element at end of queue
class Queue:
def __init__(self):
"""initialise a Queue class"""
self.items = []
self.index = len(self.items) - 1
def top(self):
"""returns the current element at front of queue"""
if self.items:
return self.items[0]
else:
raise Exception("Empty Queue")
def pop(self):
"""takes out an element from front of queue"""
if self.items:
self.items.pop(0)
else :
raise Exception("Empty Queue")
def add(self , item):
"""adds a new element at the end of queue"""
self.items.append(item)
def __str__(self):
"""returns the string representation"""
return str(self.items)
def __iter__(self):
"""iterates over the sequence"""
return self
def __next__(self):
"""returns the next value in sequence"""
if self.index == 0 :
raise StopIteration
self.index -= 1
return self.items[self.index]
queue_1 = Queue()
queue_1.add(12)
queue_1.add(11)
queue_1.add(55)
queue_1.add(66)
queue_1.add(56)
queue_1.add(43)
queue_1.add(33)
queue_1.add(88)
queue_1.add(56)
queue_1.add(34)
iter(queue_1)
for i in queue_1:
print i
print queue_1
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
The code works as intended and executes the 3 APIs specified in the problem . But it gives ""TypeError: instance has no next() method"" when i try to use next method to iterate over the values in queue. What am i missing in defining the next method?
collections.deque
. The implementation is in C rather than Python, but still worth a look. If you prefer a quick-and-simple implementation, then there's a standard approach using two stacks (stacks = lists in Python) which at least has the right complexity. \$\endgroup\$