Making polynomials representing frequency of a character in a list
You can also use a combination of Merge
and AssociationThread
:
Merge[Total][AssociationThread[# -> x^Length @ #]& /@ l]
<|"a" -> x + x^2 + x^4 + 2 x^5,
"h" -> x^2,
"d" -> x^5,
"k" -> x^4 + x^5,
"r" -> x^5,
"v" -> x^5,
"b" -> x^4 + x^5,
"c" -> x^4 + x^5,
"s" -> x^5,
"u" -> x^5|>
I think @kglr's version is better, but here is my take
GroupBy[
Flatten[
Dot[
Tally[#],
DiagonalMatrix[{1, Power[x, Length[#]]}]
] & /@ l
, 1]
, First
, Last@*Total
]