Skip to main content
Tweeted twitter.com/StackMma/status/1046867514641330176
added 10 characters in body
Source Link
kglr
  • 403.4k
  • 18
  • 501
  • 959

I have a large list of the following form

 {{1, 2} -> -1, {1, 1} -> 1, {1, 2} -> -1, {1, 6} -> 1} 

and I want to combine all of the pairs x->yx->y that share the same xx value by adding up their yy values. For the above example I want to have

 {{1, 2} -> -2, {1, 1} -> 1, {1, 6} -> 1} 

and I want to do it using patterns and ReplaceRepeatedReplaceRepeated command. I tried the following code:

 {{1, 2} -> -1, {1, 1} -> 1, {1, 2} -> -1, {1, 6} -> 1} //. HoldPattern[{x_ -> y_, a___, x_ -> z_}] -> {x -> y + z, a} 

Can anybody tell me why above code is not working and how can I do it using rules?

I have a large list of the following form

 {{1, 2} -> -1, {1, 1} -> 1, {1, 2} -> -1, {1, 6} -> 1} 

and I want to combine all of the pairs x->y that share the same x value by adding up their y values. For the above example I want to have

 {{1, 2} -> -2, {1, 1} -> 1, {1, 6} -> 1} 

and I want to do it using patterns and ReplaceRepeated command. I tried the following code:

 {{1, 2} -> -1, {1, 1} -> 1, {1, 2} -> -1, {1, 6} -> 1} //.HoldPattern[{x_ -> y_, a___, x_ -> z_}] -> {x -> y + z, a} 

Can anybody tell me why above code is not working and how can I do it using rules?

I have a large list of the following form

{{1, 2} -> -1, {1, 1} -> 1, {1, 2} -> -1, {1, 6} -> 1} 

and I want to combine all of the pairs x->y that share the same x value by adding up their y values. For the above example I want to have

{{1, 2} -> -2, {1, 1} -> 1, {1, 6} -> 1} 

and I want to do it using patterns and ReplaceRepeated command. I tried the following code:

{{1, 2} -> -1, {1, 1} -> 1, {1, 2} -> -1, {1, 6} -> 1} //. HoldPattern[{x_ -> y_, a___, x_ -> z_}] -> {x -> y + z, a} 

Can anybody tell me why above code is not working and how can I do it using rules?

Source Link

Repeated replacing elements in the list

I have a large list of the following form

 {{1, 2} -> -1, {1, 1} -> 1, {1, 2} -> -1, {1, 6} -> 1} 

and I want to combine all of the pairs x->y that share the same x value by adding up their y values. For the above example I want to have

 {{1, 2} -> -2, {1, 1} -> 1, {1, 6} -> 1} 

and I want to do it using patterns and ReplaceRepeated command. I tried the following code:

 {{1, 2} -> -1, {1, 1} -> 1, {1, 2} -> -1, {1, 6} -> 1} //.HoldPattern[{x_ -> y_, a___, x_ -> z_}] -> {x -> y + z, a} 

Can anybody tell me why above code is not working and how can I do it using rules?