Re: Re: ListDimension function
- To: mathgroup at smc.vnet.net
- Subject: [mg72623] Re: [mg72578] Re: ListDimension function
- From: "Chris Chiasson" <chris at chiasson.name>
- Date: Fri, 12 Jan 2007 06:17:52 -0500 (EST)
- References: <eo25ue$as5$1@smc.vnet.net> <200701110728.CAA24289@smc.vnet.net>
I just noticed those tests it had to pass... here is a new version: In[1]:= ListDimension[xpr_]:=With[{darg=xpr/.Except[_List|List]->Sequence[]},ListDimensionKernel@darg]; Attributes@ListDimensionKernel={HoldAllComplete}; ListDimensionKernel[Sequence[]]=0; ListDimensionKernel[darg_]:=Depth@darg-1; test1=a+b; test2={1,2,x*y}; test3={1,2,{3,0,1}}; test4={{},{},{}}; test5={{},{{1,2}},a}; ListDimension/@{test1,test2,test3,test4,test5} Out[10]= {0,1,2,2,3} On 1/11/07, carlos at colorado.edu <carlos at colorado.edu> wrote: > Many thanks to all of you who sent me solutions by direct email. > For testing purposes I organized them into 7 functions: > > ListDim1[v_]:=If[Head[v]===List,1+Max[Map[ListDim1,v],0],0]; (* Don > Taylor *) > ListDim2[lst_]:=Max[Length/@Position[lst,List]]; (* János *) > ListDim3[expr_]:=Max[Length/@Position[{expr},{___}]]; (* David Park *) > ListDim4[l_]:=Depth[DeleteCases[l,_?(!ListQ[#1]&)]]-1; (* Jean-Marc > Gulliet *) > ListDim5[e_]:=Max[Length/@Position[e,List]]; (* Carl Woll *) > ListDim6[list_List]:=Depth[list/.x_List/;(!MemberQ[x,{___}])->{}]-1;ListDim6[_]=0; > (* dh *) > ListDim7[expr_]:=Depth[0*expr]-1; (* Andrzej Kozlowski *) > > (I excluded a solution by Adriano Pascoletti, who uses 2 functions) > Here is a quick test: > > ListDimTest[e_]:={ListDim1[e],ListDim2[e],ListDim3[e],ListDim4[e],ListDim5[e], > ListDim6[e],ListDim7[e]}; > > t={1,Null,{},{1,2,3,4},{"s"+1},{{},{},{}}, {Infinity,Indefinite,{}}, > {1,{{{{{{x,y*z}}}}}},{6}}, {{{{Sqrt[1+x*y]}}}}, > {1,{2,Null+5,3},{{{4,Infinity,-4}}}}, > {0,{1,{2,{3^{1,2,3}}}}}, {c*{{1,2},{3+{x,y},4}}} } ; > Print[Table[ListDimTest[t[[i]]],{i,1,Length[t]}]//TableForm]; > > and the results are > > Infinity::indet: Indeterminate expression 0 Infinity encountered. > > Infinity::indet: Indeterminate expression 0 Infinity encountered. > > 0 -Infinity 0 0 -Infinity 0 0 > 0 -Infinity 0 0 -Infinity 0 0 > 1 1 1 1 1 1 1 > 1 1 1 1 1 1 1 > 1 1 1 1 1 1 1 > 2 2 2 2 2 2 2 > 2 2 2 2 2 2 2 > 7 7 7 8 7 7 7 > 4 4 4 7 4 4 4 > 4 4 4 5 4 4 4 > 5 5 5 5 5 5 5 > 4 4 4 6 4 4 4 > > Summary: #1, #3, #6 and #7 returned the correct value across the > board. However #7 produced a warning message when an entry > contained Infinity due to the 0*Infinite operation. It seems that the > most compact solution that works, and produces no messages, is #3. > Congratulations to David. > > BTW I found surprising that this is not provided as built-in function, > since it is such a basic operation in list preprocessing. > > -- http://chris.chiasson.name/
- References:
- Re: ListDimension function
- From: carlos@colorado.edu
- Re: ListDimension function