Re: Sum elements in a list with conditions

*To*: mathgroup at smc.vnet.net*Subject*: [mg69861] Re: Sum elements in a list with conditions*From*: dimmechan at yahoo.com*Date*: Tue, 26 Sep 2006 00:59:17 -0400 (EDT)*References*: <ef5066$mm5$1@smc.vnet.net><ef82hh$e43$1@smc.vnet.net>

Hi. In my solution of the previous post, I assumed that you want to examine only successive elements of the list. E.g. for the following list lst = {{1, 2}, {4, 5}, {4, 10}, {1, 6}, {2, 9}, {2, 3}, {1, 10}, {4, 3}, {1, 5}}; the pattern matching rule I proposed gives lst //. {a___, {x_, y_}, {x_, z_}, b___} -> {a, {x, y + z}, b} {{1, 2}, {4, 15}, {1, 6}, {2, 12}, {1, 10}, {4, 3}, {1, 5}} because only the successive elements {4, 5}, {4, 10} and {2, 9}, {2, 3} have their first element the same. If you want a rule that applied regardless of the position of the elements in the list the following rule must be used lst //. {a___, {x_, y_}, c___, {x_, z_}, b___} -> {a, {x, y + z}, c, b} {{1, 23}, {4, 18}, {2, 12}} Sincerely Dimitris Î?/Î? dimmechan at yahoo.com ÎÎ³Ï?Î±Ï?Îµ: > Your desired output can be achieved with proper > pattern matching. > > lst = {{a1, b1}, {a2, b2}, {a2, b3}, {a2, b4}, {a3, b5}, {a3, b6}}; > > lst //. {a___, {x_, y_}, {x_, z_}, b___} -> {a, {x, y + z}, b} > {{a1, b1}, {a2, b2 + b3 + b4}, {a3, b5 + b6}} > > Information["___"] > ___ (three _ characters) or BlankNullSequence[ ] is a pattern object > that can stand for any sequence of zero or more Mathematica > expressions. > ___h or BlankNullSequence[h] can stand for any sequence of expressions, > > all of which have head h. > Attributes[BlankNullSequence] = {Protected} > > Information["//."] > expr //. rules repeatedly performs replacements until expr no longer > changes. > Attributes[ReplaceRepeated] = {Protected} > Options[ReplaceRepeated] = {MaxIterations -> 65536} > > For example > > myrule = {a___, {x_, y_}, {x_, z_}, b___} -> {a, {x, y + z}, b}; > > dat=Table[Random[Integer,{1,5}],{30},{2}] > {{4,3},{4,5},{4,2},{5,4},{4,2},{5,2},{2,4},{5,1},{1,3},{4,4},{3,1},{3,5}, > {5,4},{3,1},{3,4},{2,5},{2,5},{3,5},{4,4},{2,4},{4,3},{4,5},{5,3},{5,4}, > {5,1},{1,4},{5,2},{1,3},{3,1},{4,1}} > > dat//.myrule > {{4,10},{5,4},{4,2},{5,2},{2,4},{5,1},{1,3},{4,4},{3,6},{5,4},{3,5},{2,10}, > {3,5},{4,4},{2,4},{4,8},{5,8},{1,4},{5,2},{1,3},{3,1},{4,1}} > > Regards > Dimitris