Chris's Wiki :: blog/python/SortTakesTupleKeys Commentshttps://utcc.utoronto.ca/~cks/space/blog/python/SortTakesTupleKeys?atomcommentsDWiki2018-08-09T06:59:15ZRecent comments in Chris's Wiki :: blog/python/SortTakesTupleKeys.By Mike on /blog/python/SortTakesTupleKeystag:CSpace:blog/python/SortTakesTupleKeys:3ea58f15fa65b57faff7d6539b1ca2c7f2a1797cMike<div class="wikitext"><p>For prio-queues in particular (given the example), you might also find somewhat-obscure heapq module in python useful.</p>
<p>Allows to use any list as such, using heapq.heappush(heap, (prio, value)) to add new element there, heappop() to pull highest-prio one from it and heap[0] to peek, with all the necessary ordering done efficiently and on-the-fly.</p>
</div>2018-08-09T06:59:15ZBy Clément on /blog/python/SortTakesTupleKeystag:CSpace:blog/python/SortTakesTupleKeys:d57eafa1fc9eb41ac05c7995f1a96851d324d162Clément<div class="wikitext"><p>I think the move to a tuple-based key is a net improvement. That being said, if you're in the process of porting old code, you should look at <a href="https://docs.python.org/3/library/functools.html#functools.cmp_to_key">https://docs.python.org/3/library/functools.html#functools.cmp_to_key</a> ; it takes a comparison function and returns the corresponding key function (it works by creating a custom key type K whose comparison operators are defined so that K(x) < K(y) iff cmp(x, y) < 0).</p>
</div>2018-07-10T06:57:29ZBy Phillip on /blog/python/SortTakesTupleKeystag:CSpace:blog/python/SortTakesTupleKeys:5ee30d37ea48397cb903fcd4a535ee7230e63c09Phillip<div class="wikitext"><p>I am pretty sure that sort does not have any special code for tuples. Rather, tuples are orderable (by the inherited order retrieved by comparing their fields) and the thing you've discovered is that there is no need for the key function to return the same type as went into it.</p>
</div>2018-07-10T05:47:57Z