Modular | Good for interviews | Simulating stock market matching engine with Min and Max Heaps
\nfrom heapq import heappush, heappop\n\nclass MatchingEngine(object):\n    \n    def __init__(self):\n        self.buy_orders = []  # Max heap\n        self.se
```\nfrom heapq import heappush, heappop\n\nclass MatchingEngine(object):\n    \n    def __init__(self):\n        self.buy_orders = []  # Max heap\n        self.sell_orders = [] # Min heap \n    \n    def buy(self, buy_price, quantity):\n        while len(self.sell_orders) > 0 and buy_price >= self.sell_orders[0][0] and quantity > 0:\n            sell_price, sell_quantity = heappop(self.sell_orders)\n            if sell_quantity > quantity:\n                heappush(self.sell_orders, (sell_price, sell_quantity - quantity))\n                quantity = 0\n            else:\n                quantity -= sell_quantity\n        if quantity != 0:\n            heappush(self.buy_orders, (-buy_price, quantity))\n    \n    def sell(self, sell_price, quantity):\n        while len(self.buy_orders) > 0 and sell_price <= -self.buy_orders[0][0] and quantity > 0:\n            buy_price, buy_quantity = heappop(self.buy_orders)\n            if buy_quantity > quantity:\n                heappush(self.buy_orders, (buy_price, buy_quantity - quantity))\n                quantity = 0\n            else:\n                quantity -= buy_quantity\n        if quantity != 0:\n            heappush(self.sell_orders, (sell_price, quantity))\n            \n    def get_pending_orders(self):\n        pending = lambda arr : sum(map(lambda item: item[1], arr))\n        return (pending(self.buy_orders) + pending(self.sell_orders)) % (10**9 + 7)\n    \n\nclass Solution(object):\n    def getNumberOfBacklogOrders(self, orders):\n        """\n        :type orders: List[List[int]]\n        :rtype: int\n        """\n        \n        engine = MatchingEngine()\n        \n        for price, quantity, oType in orders:\n            if oType == 0:\n                engine.buy(price, quantity)\n            else:\n                engine.sell(price, quantity)\n        \n        return engine.get_pending_orders()\n```
['Heap (Priority Queue)']