5
$\begingroup$

I want to generate all the possible combinations (commutative) of a few variables but also raised to some fixed powers.

Lets take the following example: I have three variables x,y,z. The list I want to generate will have all these variables and also their combinations of two of them, three of them, any of them raised to power 2,

{x y z, x y,x z,y z, x,y,z, 
 x^2 y^2 z^2, x^2 y^2 z,x^2 y z^2,x y^2 z^2,
 x^2 y z,x y^2 z,x y z^2,
 x^2 y^2,y^2 z^2,x^2 z^2,
 x^2 y,x y^2,x^2 z,x z^2,y^2 z,y z^2,
 x^2,y^2,z^2}

Basically all possible combinations of any number of multiplications along with they can take two powers.

Is there any easier way without incorporating nested Do loop?

$\endgroup$
5
$\begingroup$
Inner[#2^# &, Tuples[{0, 1, 2}, 3], {x, y, z}, Times]
 {1, z, z^2, y, y z, y z^2, y^2, y^2 z, y^2 z^2, x, x z, x z^2, x y, 
  x y z, x y z^2, x y^2, x y^2 z, x y^2 z^2, x^2, x^2 z, x^2 z^2, 
  x^2 y, x^2 y z, x^2 y z^2, x^2 y^2, x^2 y^2 z, x^2 y^2 z^2}
$\endgroup$
5
$\begingroup$

Here's another variation of the Tuples approach:

Tuples[Unevaluated @ Times[{1, x, x^2}, {1, y, y^2}, {1, z, z^2}]]

{1, z, z^2, y, y z, y z^2, y^2, y^2 z, y^2 z^2, x, x z, x z^2, x y, x y z, x y z^2, x y^2, x y^2 z, x y^2 z^2, x^2, x^2 z, x^2 z^2, x^2 y, x^2 y z, x^2 y z^2, x^2 y^2, x^2 y^2 z, x^2 y^2 z^2}

$\endgroup$
4
$\begingroup$

Try

Map[x^#[[1]]y^#[[2]]z^#[[3]]&,Tuples[Range[0,2],3]]

which returns

{1, z, z^2, y, y*z, y*z^2, y^2, y^2*z, y^2*z^2, x, x*z, x*z^2, x*y, x*y*z,
 x*y*z^2, x*y^2, x*y^2*z, x*y^2*z^2, x^2, x^2*z, x^2*z^2, x^2*y, x^2*y*z,
 x^2*y*z^2, x^2*y^2, x^2*y^2*z, x^2*y^2*z^2}

And because there are always multiple different ways of doing anything in Mathematica

Map[Times@@Thread[Power[{x,y,z},#]]&,Tuples[Range[0,2],3]]

There will be at least half a dozen other different ways of doing this same thing

and

Flatten[Table[x^i y^j z^k,{i,0,2},{j,0,2},{k,0,2}]]
$\endgroup$
4
$\begingroup$
Times@@({x,y,z}^#)&/@{0,1,2}~Tuples~3    

{1,z,z^2,y,y z,y z^2,y^2,y^2 z,y^2 z^2,x,x z,x z^2,x y,x y z,x y z^2,x y^2,x y^2 z,x y^2 z^2,x^2,x^2 z,x^2 z^2,x^2 y,x^2 y z,x^2 y z^2,x^2 y^2,x^2 y^2 z,x^2 y^2 z^2}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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