Re:Imperative vs. Declarative
by RyanMcGreal on Tuesday April 02, 2013 @01:48PM
(#5480892)
Aside: Python is similar to Ruby, albeit using the sorted() function rather than the sort() method.
[ Parent
| on HN ]
Re:Imperative vs. Declarative
by notaddicted on Tuesday April 02, 2013 @02:05PM
(#5481017)
Also available in python:
import heapq
n = 2
heapq.nlargest(n, vals)[n-1]
Edit: and out of morbid curiosity, here is the same implemented by a scan. It could be arranged as a single statement. swapIfGt = lambda xs, q: xs if xs[0] >= q else sorted([q]+xs[1:])
n = 2
reduce(swapIfGt, vals, [None]*n)[0]
Edit2: rewrote swapIfGtThe pedant in me squirms at seeing a quadratic-time solution to something so linear. Use a heap or a scan, sir!
Oh, now I have to yell at myself. No doubt Python's sorted is some n*logn quicksort, and not actually in quadratic time. Crow for all!
It's an adaptive mergesort-based sort: http://en.wikipedia.org/wiki/Timsort