1

For given data, arrays of table, how one can find the independent terms in Mathematica?

For example, given sets:

list={{{a,b,c},{d,e,f},{g,h,k}}
,{{a2,b2,c2},{d+e,e2,-f},{g,h,k}}
,{{a3,ab3,c*c2},{d2+e2,e,f2},{g2,h2,k}}}

I want to find the independent terms, i.e., the output for the above example should be:

a,b,c,d,e,f,g,h,k, a2,b2,c2,d2,e2,f2,g2,h2,a3,b3

The sets can have arbitrary length, and the arrays might not be the same size. But it is distinguished by, comma, and of course I want to treat $-a$ as $a$ and so on.

Can you provide me with explicit code or some key command for this purpose?

Syed
  • 52,495
  • 4
  • 30
  • 85
phy_math
  • 873
  • 4
  • 9

4 Answers4

7
Variables[list] == (Cases[list, _Symbol, ∞] // Union)

Or

Variables[
  list] == (Select[Level[list, {-1}], Not@*NumberQ] // Union)

True

Syed
  • 52,495
  • 4
  • 30
  • 85
  • 1
    Two plus the comment and counting. Nicely done! – bmf Feb 13 '23 at 14:39
  • 1
    You are right. Union will do so automatically. I have edited this out. Thanks for noticing. @rhermans – Syed Feb 13 '23 at 16:26
  • 1
    In addition, Variables "looks for variables only inside sums, products, and rational powers: Variables[{x,Sin[y]}]===Cases[{x,Sin[y]}, _Symbol, ∞] gives False, which might be important – user1066 Feb 13 '23 at 17:08
  • @user1066 Please write it up as an answer. Thanks. – Syed Feb 13 '23 at 17:26
7
Union@Select[Level[list, {-1}], Head[#]==Symbol&]
rhermans
  • 36,518
  • 4
  • 57
  • 149
6

The canonical answer has been provided. Time to find 10 more ways of doing it.

Here's the first one

complicated = {{{a, b, c}, {d, e, f}, {g, h, k}}, {{a2, b2, 
     c2}, {d + e, e2, -f}, {g, h, k}}, {{a3, ab3, c*c2}, {d2 + e2, e, 
     f2}, {g2, h2, k}}};

Then, the following does the trick

DeleteDuplicates[Flatten[List @@@ Flatten[complicated]]] /. 
 a_ /; TrueQ[NumberQ[a]] -> Nothing

{a, b, c, d, e, f, g, h, k, a2, b2, c2, e2, a3, ab3, d2, f2, g2, h2}

bmf
  • 15,157
  • 2
  • 26
  • 63
5

Using GroupBy and Lookup:

Sort@Lookup[GroupBy[Level[list, {-1}], NumericQ, DeleteDuplicates], False]

({a, a2, a3, ab3, b, b2, c, c2, d, d2, e, e2, f, f2, g, g2, h, h2, k})

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44