Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
3.17. Implementing a Deque in Python¶
As we have done in previous sections, we will create a new class for the implementation of the abstract data type deque. Again, the Python list will provide a very nice set of methods upon which to build the details of the deque. Our implementation (Listing 1) will assume that the rear of the deque is at position 0 in the list.
1class Deque: 2 """Deque implementation as a list""" 3 4 def __init__(self): 5 """Create new deque""" 6 self._items =  7 8 def is_empty(self): 9 """Check if the deque is empty""" 10 return not bool(self._items) 11 12 def add_front(self, item): 13 """Add an item to the front of the deque""" 14 self._items.append(item) 15 16 def add_rear(self, item): 17 """Add an item to the rear of the deque""" 18 self._items.insert(0, item) 19 20 def remove_front(self): 21 """Remove an item from the front of the deque""" 22 return self._items.pop() 23 24 def remove_rear(self): 25 """Remove an item from the rear of the deque""" 26 return self._items.pop(0) 27 28 def size(self): 29 """Get the number of items in the deque""" 30 return len(self._items)
remove_front we use the
pop method to remove the last element
from the list. However, in
pop(0) method must
remove the first element of the list. Likewise, we need to use the
insert method (line 12) in
add_rear since the
assumes the addition of a new element to the end of the list.
CodeLens 1 shows the
Deque class in
action as we perform the sequence of operations from
You can see many similarities to Python code already described for stacks and queues. You are also likely to observe that in this implementation adding and removing items from the front is \(O(1)\) whereas adding and removing from the rear is \(O(n)\). This is to be expected given the common operations that appear for adding and removing items. Again, the important thing is to be certain that we know where the front and rear are assigned in the implementation.