Suppose I have the following list:

l={{"a"}, {"a", "h"}, {"a", "d", "k", "r", "v"}, {"a", "b", "c", 
  "k"}, {"a", "b", "c", "s", "u"}}

this list made of the following letters:

In: l // Flatten // DeleteDuplicates // Sort    
Out: {"a", "b", "c", "d", "h", "k", "r", "s", "u", "v"}

For each letter I want to make a polynomial such that it calculates how many times they appear in elements of different lengths, for example "a" appears 1 time in element of length 1, 1 time in element of size 2, 2 times in element of size 5 and 1 times in element of size 4. thus the polynomial of it should be like:

<|"a" -> x+x^2+x^4+2x^5|>

where the power of polynomial are corresponding to the length of element and coefficient would be the frequency of a in the elements with specific lengths.

  • $\begingroup$ Thanks for accepting my answer, but I think you were too hasty doing that. While accepting is one of the things to do after your question is answered, we recommend that users should test answers before voting and wait 24 hours before accepting the best one. That allows people in all timezones to answer your question and an opportunity for other users to point alternatives, caveats or limitations of the available answers. In this case @kglr gave a better answer than mine. $\endgroup$
    – rhermans
    Jul 10, 2019 at 19:39

2 Answers 2


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

     DiagonalMatrix[{1, Power[x, Length[#]]}]
     ] & /@ l
  , 1]
 , First
 , Last@*Total

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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