Deque
  • An ordered collection of items where items are added and removed from either end, either front or rear
  • Implementation with list
    # DequeModule.py
    #!/usr/bin/python3
    class Deque(object):
        def __init__(self):
            self.items = []
    
        def isEmpty(self):
            return len(self.items) == 0
    
        def addFront(self, v):
            try:
                self.items.append(v)
                return True
            except Exception as err:
                return False
    
        def addRear(self, v):
            try:
                self.items.insert(0, v)
                return True
            except Exception as err:
                return False
    
        def removeFront(self):
            try:
                return self.items.pop()
            except Exception as err:
                return None
    
        def removeRear(self):
            try:
                return self.items.pop(0)
            except Exception as err:
                return None
    
        def size(self):
            return len(self.items)
    
        def __str__(self):
            s = 'rear ->'
    
            output = []
    
            for item in self.items:
                output.append(str(item))
    
            s += '->'.join(output)
    
            s += '-> front'
    
            return s
                
    #!/usr/bin/python3
    from DequeModule import Deque
    
    def main():
        d = Deque()
    
        print(d.isEmpty()) # True
    
        d.addRear(4)
        d.addRear('dog')
        d.addFront('cat')
        d.addFront(True)
    
        print(d) # rear ->dog->4->cat->True-> front
    
        print(d.size()) # 4
        print(d.isEmpty()) # False
    
        d.addRear(8.4)
        print(d.removeRear()) # 8.4
        print(d.removeFront()) # True
    
        print(d) # rear ->dog->4->cat-> front
    
    if __name__ == '__main__':
        main()
                
    Reference
  • Problem Solving with Algorithms and Data Structures using Python