Re: Sum elements in a list with conditions
- To: mathgroup at smc.vnet.net
- Subject: [mg69873] Re: [mg69828] Sum elements in a list with conditions
- From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
- Date: Tue, 26 Sep 2006 00:59:39 -0400 (EDT)
On 24 Sep 2006, at 12:45, Guillermo Sanchez wrote: > Dear group > I have a pair of elements list. The second elements of the list should > be summed when the first element of the pairs are equals. Example > > Given > > {{a1, b1},{a2,b2},{a2,b3},{a2,b4},{a3, b5}, {a3, b6}} > > the output should be > > {{a1, b1},{a2, b2+b3+b4},{a3, b5+b6}} > > Thanks > > Guillermo > Just for fun: here is a solution that is, I think, entirely different from all the others that have been posted. List@@@(List@@(Simplify[Plus@@(Times@@@{{a1, b1},{a2,b2},{a2,b3}, {a2,b4},{a3, b5}, {a3, b6}})])) {{a1, b1}, {a2, b2 + b3 + b4}, {a3, b5 + b6}} It will only work if the elements of the original lists are symbols but one can modify it to work with numbers. However, this way of programming is in general inefficient so the above is only meant as an example of the kind of programming that is unique to computer algebra systems. Andrzej Kozlowski