1
$\begingroup$

I have a list of elements and a large expression in these elements. I would like to count the occurrences of each of the list elements in the expression. Say, the list is {a1,a2,a3,...,an} and the expression is 2a1 - 3a2^2*a5 - 7x^2 a4 + 3a1*a4 + ... so the output would be something like

{{a1,2},{a2,1},{a3,0},{a4,2},...}.

I have tried to use Count and Select, but am not getting the required results. Any help is appreciated.

$\endgroup$
3
$\begingroup$
expr = 2 a1 - 3 a2^2*a5 - 7 x^2 a4 + 3 a1*a4;
lst = {a1, a2, a3, a4}; 

Transpose[{lst, Lookup[Counts[Level[expr, {-1}]], lst, 0]}]

{{a1, 2}, {a2, 1}, {a3, 0}, {a4, 2}}

or

Transpose[{lst, Count[Level[expr, {-1}], #] & /@ lst}]

{{a1, 2}, {a2, 1}, {a3, 0}, {a4, 2}}

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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