4 ms·
Aside: Python is similar to Ruby, albeit using the sorted() function rather than the sort() method. sorted(vals)[-2]
by RyanMcGreal 14y ago
Aside: Python is similar to Ruby, albeit using the sorted() function rather than the sort() method.
sorted(vals)[-2]
- notaddicted 14y agoAlso 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 swapIfGt
- textminer 14y agoThe pedant in me squirms at seeing a quadratic-time solution to something so linear. Use a heap or a scan, sir!
- textminer 14y agoOh, 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!