toy list processing problem: collect similar terms

WJ w_a_x_man at yahoo.com
Thu Feb 10 16:03:01 EST 2011


Pascal J. Bourguignon wrote:

> Xah Lee <xahlee at gmail.com> writes:
> 
> 
> > here's a interesting toy list processing problem.
> > 
> > I have a list of lists, where each sublist is labelled by
> > a number. I need to collect together the contents of all sublists
> > sharing
> > the same label. So if I have the list
> > 
> > ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4
> > q r) (5 s t))
> > 
> > where the first element of each sublist is the label, I need to
> > produce:
> > 
> > output:
> > ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
> > 
> > a Mathematica solution is here:
> > http://xahlee.org/UnixResource_dir/writ/notations_mma.html
> > 
> > R5RS Scheme lisp solution:
> > http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work
> > _gmail.scm by Sourav Mukherjee
> > 
> > also, a Common Lisp solution can be found here:
> > http://groups.google.com/group/comp.lang.lisp/browse_frm/thread/5d1d
> > ed8824bc750b?
> 
> It's too complex. Just write:
> 
> (let ((list '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) 
>               (2 o p) (4 q r) (5 s t))))
> 
>   (mapcar (lambda (class) (reduce (function append) class :key
> (function rest)))
> (com.informatimago.common-lisp.list:equivalence-classes list :key
> (function first)))
> 
>    )
> 
> --> ((S T) (Q R M N) (G H) (O P K L E F) (I J C D) (A B))

Clojure:

(def groups '((0 a b)(1 c d)(2 e f)(3 g h)(1 i j)(2 k l)(4 m n)
(2 o p)(4 q r) (5 s t)))

Using group-by:

(map (fn[[k v]](flatten (map rest v))) (group-by first groups))

Using reduce:

(map #(flatten(rest %)) (reduce (fn[h [k & v]]
  (merge-with concat h {k v})) {} groups)) 




More information about the Python-list mailing list