I am converting some codes from Mathematica into Python. Suppose I have the following list:
l = [["x1", "x2", "x3"], ["x4", "x5", "x6"], ["x7", "x8"], ["x9",
"x10"], ["x11"]]
I want to turn above into a polynomial such that the length of each element in the list would be the power of the variable x. In Mathematica I do this by:
Total[x^Map[Length, l]]
which gives:
Output: x + 2 x^2 + 2 x^3
This means I have 1 element in list l with length 1, 2 elements with length 2 and 2 elements with length 3. In Python I have tried the following:
sum(x**map(len(l), l))
But this does not work as x is not defined, also I tried with "x", and it does not work either. I wonder how does one translate such code.
You could create a string according to your specifications, e.g., like this:
from itertools import groupby
l = [["x1", "x2", "x3"], ["x7", "x8"], ["x9", "x10"], ["x4", "x5", "x6"], ["x11"]]
g = groupby(sorted(l, key = len), key = len)
s = " + ".join([" ".join([str(len(list(i))), "* x **", str(j)]) for j, i in g])
print(s)
#output
#1 * x ** 1 + 2 * x ** 2 + 2 * x ** 3
But this is just a string, while I assume from your question that you want to evaluate this formula later.