Re: LeafCount
- To: mathgroup at smc.vnet.net
- Subject: [mg25958] Re: LeafCount
- From: "Allan Hayes" <hay at haystack.demon.co.uk>
- Date: Tue, 14 Nov 2000 03:46:52 -0500 (EST)
- References: <8ug9h6$idn@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Will ?LeafCount "LeafCount[expr] gives the total number of indivisible subexpressions in \ expr." So the following seems correct to me, since the heads Plus and Times must be counted. Plus[x, Times[y, z]] // LeafCount 5 Re: myLeafCount[expr_] := Length[Flatten[Hold[expr] /. x_ :> List /; Head[x] == Symbol]] The Hold may not be doing what you want, since expr will have been evaluated before being passed. Solution: use attribute HoldAll (or Hold First). Also, why not x_Symbol. SetAttributes[myLeafCount2, HoldAll] myLeafCount2[expr_] := Length[Flatten[Hold[expr] /. x_ Symbol :> List ]] However these are technicalities. The following seem to have a bearing on the difference. Level[Plus[2, Times[y, z]], {-1}] {2, y, z} Level[Plus[2, Times[y, z]], {-1}, Heads -> True] {Plus, 2, Times, y, z} -- Allan --------------------- Allan Hayes Mathematica Training and Consulting Leicester UK www.haystack.demon.co.uk hay at haystack.demon.co.uk Voice: +44 (0)116 271 4198 Fax: +44 (0)870 164 0565 "Will Self" <wself at msubillings.edu> wrote in message news:8ug9h6$idn at smc.vnet.net... > In the expression Plus[x, Times[y, z]] I would say that there are 3 > terminal nodes (leaves), x, y, and z. The built-in function LeafCount, > which purports to count the number of terminal nodes in the expression > tree, actually counts *all* the nodes. So > LeafCount[Plus[x, Times[y, z]]] ---> 5 > Am I missing something here, or is it true that LeafCount is wrongly > described in the Mathematica Book? > > Here is mine: > > myLeafCount[expr_]:= > Length[Flatten[Hold[expr] /. x_ :> List /; Head[x] == Symbol]] > > Does anyone see anything wrong with this? Or have another suggestion? > > Will Self > private email replies appreciated > > > Sent via Deja.com http://www.deja.com/ > Before you buy. >