0
$\begingroup$

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.

$\endgroup$
4
  • $\begingroup$ Take a look at StringTemplate and friends. $\endgroup$
    – Kuba
    Commented Feb 19, 2018 at 18:40
  • $\begingroup$ 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? $\endgroup$ Commented Feb 19, 2018 at 21:25
  • $\begingroup$ do you mean (y^c) *z or y^(c*z)? $\endgroup$
    – Alucard
    Commented Feb 19, 2018 at 22:08
  • $\begingroup$ It is (y^c)*z. I know it seems like a typo. $\endgroup$ Commented Feb 20, 2018 at 0:32

1 Answer 1

1
$\begingroup$
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}]
$\endgroup$
4
  • $\begingroup$ 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 $\endgroup$
    – Alucard
    Commented Feb 19, 2018 at 22:04
  • $\begingroup$ @Alucard Yes. I'm assuming a typo propagated by copy and paste. But perhaps its not. $\endgroup$
    – Alan
    Commented Feb 19, 2018 at 22:36
  • $\begingroup$ I know it appears to be, but it's not a typo $\endgroup$ Commented Feb 20, 2018 at 0:46
  • $\begingroup$ @KennethEaves Then see the edit. $\endgroup$
    – Alan
    Commented Feb 20, 2018 at 3:00

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.