1
$\begingroup$

The title pretty much says it. I want to map over the solutions returned by Solve but want to avoid calculating the same thing over and over again.

e.g.

sol = Solve[(x - 1)^4*(x + 1)^7 == 0, x]
(*=>{{x -> -1}, {x -> -1}, {x -> -1}, {x -> -1}, {x -> -1}, {x -> -1}, 
     {x -> -1}, {x -> 1}, {x -> 1}, {x -> 1}, {x -> 1}}*)
heavyTask[#] &/@ sol

However, I would like to keep track of the number of solutions. Therefore, I thought the best way would be to have

sol={{{x -> 1},4}}

The only way I have been able to do it

DeleteDuplicates[{#, Count[sol, #]} & /@ sol]

As you can see my solution is calling Count for every element in the list. This usually isn't a problem as I work with small lists only. Nevertheless I could imagine that there are better ways to do it?

$\endgroup$
  • 4
    $\begingroup$ Check out the Tally command. reference.wolfram.com/language/ref/Tally.html?q=Tally $\endgroup$ – Gustavo Delfino Feb 4 '15 at 12:32
  • $\begingroup$ That was easy. I need to work on my google skills. Didn't come across this command. $\endgroup$ – NOhs Feb 4 '15 at 12:41
  • 1
    $\begingroup$ @Mr Z why not to formulate your comment as an answer? Otherwise this question will stay without answer forever. $\endgroup$ – Alexei Boulbitch Feb 4 '15 at 13:00
  • $\begingroup$ I think this is not easily found in the documentation. One would need to know what to search for and "tally" does not immediately come to mind. In more recent versions were also have Counts (which is a more intuitive name). If the question were not closed, someone could post that as an answer as well. $\endgroup$ – Szabolcs Apr 1 '19 at 12:35
3
$\begingroup$

As Gustavo pointed out in the comments above there is already a build-in function in Mathematica which does exactly what I asked for:

Tally[Solve[(x - 1)^4*(x + 1)^7 == 0, x]]
(*=>{{{x -> -1}, 7}, {{x -> 1}, 4}}*)
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.