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


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

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}}


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

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

| improve this answer | |

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.