Re: Take n largest items

Slobodan Blazeski <slobodan.blazeski@xxxxxxxxx> writes:

I need to take the n largest items from a list in order of
appearance. Something like:

(defvar *foo* '((a 11) (b 2) (c 7) (d -2) (e 0) (f 33)))

(take 3 :key #'second)
((a 11) (b 2) (f 33))

Corrected to (take 3 *foo* :key #'second)
((a 11) (c 7) (f 33)).

OK, here's another solution to throw into the mix.

(defun take (n list &key (key #'identity))
(if (< n (length list))
(let* ((sorted-list (sort (copy-seq list) #'> :key key))
(top-n (subseq sorted-list 0 n)))
(remove-if-not #'(lambda (x) (find x top-n)) list))

BTW, I doubt that it is an optimal solution.

Thomas A. Russ, USC/Information Sciences Institute