Hacker News new | ask | show | jobs
by RyanMcGreal 4819 days ago
Aside: Python is similar to Ruby, albeit using the sorted() function rather than the sort() method.

    sorted(vals)[-2]
2 comments

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 swapIfGt
The 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
Still, I'd rather have a loop and be linear than using a sort and being linearithmic.