Re: Extract values and multilpicities from list
- To: mathgroup at smc.vnet.net
- Subject: [mg64875] Re: [mg64849] Extract values and multilpicities from list
- From: Bob Hanlon <hanlonr at cox.net>
- Date: Mon, 6 Mar 2006 05:01:32 -0500 (EST)
- Reply-to: hanlonr at cox.net
- Sender: owner-wri-mathgroup at wolfram.com
lstIn={2,3,4,4,2,1,1,5,4};
{#,Count[lstIn,#]}&/@Union@lstIn
{{1, 2}, {2, 2}, {3, 1}, {4, 3}, {5, 1}}
{#[[1]],Length[#]}&/@Split@Sort@lstIn
{{1, 2}, {2, 2}, {3, 1}, {4, 3}, {5, 1}}
%==%%
True
While the first method is slightly shorter, the second method is considerably
faster.
lstIn=Table[Random[Integer,{1,5}],{10000}];
Timing[{#,Count[lstIn,#]}&/@Union@lstIn]
{0.031166999999999945*Second, {{1, 2017}, {2, 2047},
{3, 1987}, {4, 1978}, {5, 1971}}}
Timing[{#[[1]],Length[#]}&/@Split@Sort@lstIn]
{0.00836400000000026*Second, {{1, 2017}, {2, 2047},
{3, 1987}, {4, 1978}, {5, 1971}}}
{%[[2]]==%%[[2]],%%[[1]]/%[[1]]}
{True,3.72633}
Bob Hanlon
>
> From: "Dr. Wolfgang Hintze" <weh at snafu.de>
To: mathgroup at smc.vnet.net
> Subject: [mg64875] [mg64849] Extract values and multilpicities from list
>
> Given a list of integers which may repeat, e.g.
>
> lstIn = {2,3,4,4,2,1,1,5,4}
>
> provide a list of different values and their respective multiplicities,
> in the example,
>
> LstOut= {{1,2},{2,2},{3,1},{4,3},{5,1}}
>
> Who finds the shortest function doing this task in general?
>
> Thanks.
>
> Best regards,
> Wolfgang
>
>