{"id":81,"date":"2010-07-19T17:18:55","date_gmt":"2010-07-19T15:18:55","guid":{"rendered":"http:\/\/joernhees.de\/blog\/?p=81"},"modified":"2016-09-28T20:34:56","modified_gmt":"2016-09-28T18:34:56","slug":"min-heap-in-python","status":"publish","type":"post","link":"https:\/\/joernhees.de\/blog\/2010\/07\/19\/min-heap-in-python\/","title":{"rendered":"Min-Heap in Python"},"content":{"rendered":"<p>I recently wanted to implement a small event system where events can have different priorities. So for example the event with highest priority (lowest value) should be handled first.<br \/>\nPython comes with a heapq module which can transform a list into a heap in a way that it stays a list, but fulfills all heap constraints. Nevertheless you might want to wrap the heap like this, so you can do nice stuff:<\/p>\n<pre><code class=\"python\">import heapq\nclass Heap(object):\n    \"\"\" A neat min-heap wrapper which allows storing items by priority\n        and get the lowest item out first (pop()).\n        Also implements the iterator-methods, so can be used in a for\n        loop, which will loop through all items in increasing priority order.\n        Remember that accessing the items like this will iteratively call\n        pop(), and hence empties the heap! \"\"\"\n\n    def __init__(self):\n        \"\"\" create a new min-heap. \"\"\"\n        self._heap = []\n\n    def push(self, priority, item):\n        \"\"\" Push an item with priority into the heap.\n            Priority 0 is the highest, which means that such an item will\n            be popped first.\"\"\"\n        assert priority &gt;= 0\n        heapq.heappush(self._heap, (priority, item))\n\n    def pop(self):\n        \"\"\" Returns the item with lowest priority. \"\"\"\n        item = heapq.heappop(self._heap)[1] # (prio, item)[1] == item\n        return item\n\n    def __len__(self):\n        return len(self._heap)\n\n    def __iter__(self):\n        \"\"\" Get all elements ordered by asc. priority. \"\"\"\n        return self\n\n    def next(self):\n        \"\"\" Get all elements ordered by their priority (lowest first). \"\"\"\n        try:\n            return self.pop()\n        except IndexError:\n            raise StopIteration\n<\/code><\/pre>\n<p>With this one could do the following:<\/p>\n<pre><code class=\"python\">h = Heap()\n# add some nonsense:\nh.push(10, \"I'm a large one\")\nh.push(20, \"Actually I'm larger\")\nh.push(5, \"size is not everything\")\nh.push(0, \"which size?\")\n\n# get it out in a cool way:\nfor item in h:\n   print item\n\n# prints:\n# which size?\n# size is not everything\n# I'm a large one\n# Actually I'm larger\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>I recently wanted to implement a small event system where events can have different priorities. So for example the event with highest priority (lowest value) should be handled first. Python comes with a heapq module which can transform a list into a heap in a way that it stays a list, but fulfills all heap [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":""},"categories":[2],"tags":[49,64,65,105,132,183,194],"jetpack_featured_media_url":"","jetpack_shortlink":"https:\/\/wp.me\/pYA5n-1j","jetpack-related-posts":[{"id":91,"url":"https:\/\/joernhees.de\/blog\/2010\/07\/21\/sort-python-dict-by-values\/","url_meta":{"origin":81,"position":0},"title":"Sort python dictionaries by values","date":"2010-07-21","format":false,"excerpt":"Perhaps you already encountered a problem like the following one yourself: You have a large list of items (let's say URIs for this example) and want to sum up how often they were viewed (or edited or... whatever). A small one-shot solution in python looks like the following and uses\u2026","rel":"","context":"In &quot;Coding&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":566,"url":"https:\/\/joernhees.de\/blog\/2014\/02\/25\/scientific-python-on-mac-os-x-10-9-with-homebrew\/","url_meta":{"origin":81,"position":1},"title":"Scientific Python on Mac OS X 10.9+ with homebrew","date":"2014-02-25","format":false,"excerpt":"Scientific python setup guide for Mac OS X 10.9 Mavericks with homebrew","rel":"","context":"In &quot;Coding&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":104,"url":"https:\/\/joernhees.de\/blog\/2010\/07\/22\/precision-recall-diagrams-including-fmeasure\/","url_meta":{"origin":81,"position":2},"title":"Precision-Recall diagrams including F-Measure height lines","date":"2010-07-22","format":false,"excerpt":"Today I was asked how to generate Recall-Precision diagrams including the f-measure values as height-lines from within python. Actually Gunnar was the one who had this idea quite a while ago, but constantly writing things into files, then loading them with his R code to visualize them, made me create\u2026","rel":"","context":"In &quot;Coding&quot;","img":{"alt_text":"","src":"https:\/\/i2.wp.com\/joernhees.de\/blog\/wp-content\/uploads\/2010\/07\/RecallPrecisionDiagram-300x223.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":256,"url":"https:\/\/joernhees.de\/blog\/2010\/09\/21\/how-to-convert-hex-strings-to-binary-ascii-strings-in-python-incl-8bit-space\/","url_meta":{"origin":81,"position":3},"title":"How to convert hex strings to binary ascii strings in python (incl. 8bit space)","date":"2010-09-21","format":false,"excerpt":"As i come across this again and again: How do you turn a hex string like \"c3a4c3b6c3bc\" into a nice binary string like this: \"11000011 10100100 11000011 10110110 11000011 10111100\"? The solution is based on the Python 2.6 new string formatting: >>> \"{0:8b}\".format(int(\"c3\",16)) '11000011' Which can be decomposed into 4\u2026","rel":"","context":"In &quot;Coding&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":19,"url":"https:\/\/joernhees.de\/blog\/2010\/06\/28\/python-and-encoding\/","url_meta":{"origin":81,"position":4},"title":"Python and encoding","date":"2010-06-28","format":false,"excerpt":"Well, first real post, so let's start easy. I've been working a lot with python lately, and came across a nice short How to Use UTF-8 with Python which also makes the difference between unicode and utf8 very clear. The howto also links to another valuable source: Characters vs. Bytes,\u2026","rel":"","context":"In &quot;Coding&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":526,"url":"https:\/\/joernhees.de\/blog\/2013\/06\/08\/mac-os-x-10-8-scientific-python-with-homebrew\/","url_meta":{"origin":81,"position":5},"title":"Scientific Python on Mac OS X 10.8 with homebrew","date":"2013-06-08","format":false,"excerpt":"(newer version of this guide) A step-by-step installation guide to setup a scientific python environment based on Mac OS X and homebrew. Needless to say: Make a backup (Timemachine) First install homebrew. Follow their instructions, then come back here. If you don't have a clean install, some of the following\u2026","rel":"","context":"In &quot;Coding&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/joernhees.de\/blog\/wp-json\/wp\/v2\/posts\/81"}],"collection":[{"href":"https:\/\/joernhees.de\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/joernhees.de\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/joernhees.de\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/joernhees.de\/blog\/wp-json\/wp\/v2\/comments?post=81"}],"version-history":[{"count":2,"href":"https:\/\/joernhees.de\/blog\/wp-json\/wp\/v2\/posts\/81\/revisions"}],"predecessor-version":[{"id":769,"href":"https:\/\/joernhees.de\/blog\/wp-json\/wp\/v2\/posts\/81\/revisions\/769"}],"wp:attachment":[{"href":"https:\/\/joernhees.de\/blog\/wp-json\/wp\/v2\/media?parent=81"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/joernhees.de\/blog\/wp-json\/wp\/v2\/categories?post=81"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/joernhees.de\/blog\/wp-json\/wp\/v2\/tags?post=81"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}