3
$\begingroup$

I have expressions like these:

expr1 = -2 a Z[-2] - 2 b Z[-1] - 2 Z[-1] + a Z[-1]
expr2 = -2 a Z[-2] - 2 b Z[-1] - 2 Z[-1] + a Z[-1] + c Z[0]
expr3 = -2 a Z[-2] - 2 c Z[-1] - 2 Z[-1] + a Z[-1] + c Z[0]

and I want to find out whether an expression contains as coefficient a, b and c. So what I want is a function f[expr], such that

f[expr1] (* false because it only contains a and b *)
f[expr2] (* true because it contains a, b and c *)
f[expr3] (* false because it only contains a and c *)

The only way I can think of is converting it to a string and do a string-search, but I'm sure there must be a more clever way. I was trying to use Case[], but I was not able to find a solution yet.


Edit: There are several different solutions, I tested them on speed. Run each of the functions 100.000 times (with one argument only, in case the {a,b,c}-list was a function-argument, it was replaced to be constant - for fair comparison) with the expr1, expr2, expr3 expressions.

Results:

  • Dr. belisarius: 11.3443515 sec
  • Bill: 2.0469818 sec
  • eldo's 1st: 3.6095660 sec
  • eldo's 2nd: 2.4532568 sec
  • Suba Thomas: 6.8753645 sec
  • (Algohi: My Mathmatica9 does not support SubsetQ unfortunatly.)

The fastest solution will get the acceptance-reward, after roughly 24hours of the original questions. Thanks for the infos and the fun :-)

$\endgroup$
4
$\begingroup$
check[expr_, vars_]:= Not[Or @@ Map[FreeQ[expr, #] &, vars]];
check[expr1, {a, b, c}]
check[expr2, {a, b, c}]
check[expr3, {a, b, c}]

(* False, True, False *)

$\endgroup$
4
$\begingroup$
f[expr_] := Count[D[expr, {{a, b, c}}], 0] == 0
f /@ {expr1, expr2, expr3}

{False, True, False}

$\endgroup$
  • $\begingroup$ wow that is an unusual solution :) $\endgroup$ – NicoDean Jan 13 '16 at 0:24
  • $\begingroup$ Turns out to also have the fewest characters (so far). But not the fastest! $\endgroup$ – Suba Thomas Jan 13 '16 at 20:14
3
$\begingroup$
f[x_] := Not[Or @@ (PossibleZeroQ /@ Last@CoefficientArrays[x, {a, b, c}])]
f /@ {expr1, expr2, expr3}
(* {False, True, False} *)
$\endgroup$
2
$\begingroup$
f[expr_, var_List] := SubsetQ[Level[expr, {-1}], var]
$\endgroup$
2
$\begingroup$
Table[Union@Flatten@Map[Cases[ex, #, Infinity] &, {a, b, c}] == 
 {a, b, c}, {ex, {expr1, expr2, expr3}}]

{False, True, False}

Or

f[ex_] := 
 Union@Flatten@Map[Cases[ex, #, Infinity] &, {a, b, c}] == {a, b, c}

f /@ {expr1, expr2, expr3}

{False, True, False}

Or

 f[ex_] := And @@ Map[MemberQ[ex, #, Infinity] &, {a, b, c}]

 f /@ {expr1, expr2, expr3}

{False, True, False}

$\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.