Re: List complement operator
- To: mathgroup at smc.vnet.net
- Subject: [mg84978] Re: List complement operator
- From: Szabolcs Horvát <szhorvat at gmail.com>
- Date: Mon, 21 Jan 2008 07:00:26 -0500 (EST)
- References: <fn1ndi$97t$1@smc.vnet.net>
zac wrote: > Dear group, > > I'm loooking for an elegant and efficient way to subtract a list (not > a set) from an other one. > > a = {1, 1, 1, 2, 3, 3, 4, 5, 5, 5, 2, 6, 7, 7}; > b = {1, 2, 2, 3, 4, 7, 8}; > > Complement[a,b] returns {5, 6}, as expected. However I would like to > treat each entry as a discrete element, therefore my target result is: > {1, 1, 3, 5, 5, 5, 6, 7}. Union can not be used, although Sort is > allowed (ie. whether the result is sorted or not is of no concern). > Any idea? Hi Istvan, This is a quick-and-dirty solution, not particularly efficient if you have many different elements, but if we're lucky, it might just be fast enough for your application: lc[a_, b_] := Join @@ ( Table[#1, {#2}] & @@@ Transpose@With[{u = Union[a, b]}, {u, Last /@ Sort@Tally@Join[a, u] - Last /@ Sort@Tally@Join[b, u]} ] ) The solution just reflects the way I interpreted the problem: Remove as many 2's from 'a' as are present in 'b'. -- Szabolcs