class Deque(object): """This is the Deque data structure. Methods: append(): Append a Node with given value to the tail. appendleft(): Push a Node with given value to the head. pop(): Remove the node from the head, return the value. popleft(): Remove the node from the tail, return the value. peek(): Return the value from the tail node. peekleft(): Return the value from the head node. """ def __init__(self, maybe_an_iterable=None): """Initialize a deque data structure.""" self._container = DblLinkedList(maybe_an_iterable) def append(self, val): """Append a node with given value to the tail.""" self._container.append(val) def appendleft(self, val): """Append a node with given value to the head.""" self._container.push(val) def pop(self): """Remove the node from the tail and return the value.""" try: return self._container.shift() except IndexError: raise IndexError("Cannot pop from empty Deque.") def popleft(self): """Remove the node from the head and return the value.""" try: return self._container.pop() except IndexError: raise IndexError("Cannot popleft from empty Deque.") def peek(self): """Give the value for the tail node.""" try: return self._container.tail.value except AttributeError: return None def peekleft(self): """Give the value for the head node.""" try: return self._container.head.value except AttributeError: return None def size(self): """Return the length of the deque.""" return self._container._size def __len__(self): """Call the size method.""" return self.size()
class Deque(object): """Establish class for deque. Methods composed from dbl_linked_list.""" def __init__(self, seq=None): """Initialize deque.""" self._deque = DblLinkedList(seq) def append(self, val): """Append value to end of deque.""" self._deque.append(val) def appendleft(self, val): """Append value to front of deque.""" self._deque.insert(val) def pop(self): """Remove last item from deque and return its value.""" try: return self._deque.shift() except IndexError: raise IndexError("Cannot pop from end of an empty deque.") def popleft(self): """Remove first item from deque and return its value.""" try: return self._deque.pop() except IndexError: raise IndexError("Cannot pop from head of an empty deque.") def peek(self): """Return value of last item in deque.""" try: return self._deque.tail.val except AttributeError: return None def peekleft(self): """Return value of first item in deque.""" try: return self._deque.head.val except AttributeError: return None def size(self): """Calculate number of items in the deque and return it.""" cur_node = self._deque.head counter = 0 while cur_node: counter += 1 cur_node = cur_node.next_node return counter
def test_shift(seq, shift_val, tail_val): """Test the shift method of DblLinkedList class.""" from dbl_linked_list import DblLinkedList test_list = DblLinkedList(seq) assert test_list.shift() == shift_val assert test_list.tail.val == tail_val