List to expression

I am trying to take a list {a,b,c,d,e,f,g,h} and turn it into the following expression:

w^a+x^b+y^c*z+z^d "with weights:" {e,f,g,h}


Note that in the expression w,x,y and z will remain those variables.

Example:

{2,4,7,3,5,3,4,2}


would become:

w^2+x^4+y^7*z+z^3 "with weights:" {5,3,4,2}


But I don't need the quotation marks around with weights.

• Take a look at StringTemplate and friends.
– Kuba
Commented Feb 19, 2018 at 18:40
• Perfect! Now where I put the numbers in for StringTemplate, they go in as elements separated by commas, and not as a list. How do I take a list, and remove the curly brackets? Commented Feb 19, 2018 at 21:25
• do you mean (y^c) *z or y^(c*z)? Commented Feb 19, 2018 at 22:08
• It is (y^c)*z. I know it seems like a typo. Commented Feb 20, 2018 at 0:32

lst2expr[x_List, vars_List] := With[{
tmp = StringTemplate[" with weights: "],
powers = Take[x, Length[vars]],
wts = Drop[x, Length[vars]]
},
tmp[ToString@InputForm[vars^powers], wts]
]


Try it out:

lst2expr[{2, 4, 7, 3, 5, 3, 4, 2}, {w, x, y, z}]


Edit:

The solution above assumes you have a typo in the expression. If not, you can use the following, which is less general but matches your suggested output.

lst2expr02[x_List] := With[{
tmp = StringTemplate["w^+x^+y^*z+z^ with weights: "],
powers = Take[x, 4],
wts = Drop[x, 4]},
tmp[Sequence @@ powers, wts]
]


Try it out:

lst2expr02[{2, 4, 7, 3, 5, 3, 4, 2}]

• either OP has made the same typo in 2 different spots or your code produce a result different from what OP asked: take a look at the third term Commented Feb 19, 2018 at 22:04
• @Alucard Yes. I'm assuming a typo propagated by copy and paste. But perhaps its not.
– Alan
Commented Feb 19, 2018 at 22:36
• I know it appears to be, but it's not a typo Commented Feb 20, 2018 at 0:46
• @KennethEaves Then see the edit.
– Alan
Commented Feb 20, 2018 at 3:00