# Removing terms with more than 2 variables

Say I have the variable

x = a + a b + a b c + a b c d + ....


What is the easiest way to remove all terms with more than 2 variables? Up until now, I have used

x = a + a b + a b c + a b c d
coeffs = CoefficientRules[x, {a, b, c, d}];
selects = Select[coeffs, Total@(#[[1]]) <= 2 &];
x = FromCoefficientRules[selects, {a, b, c, d}]


Which works, but it requires me to manually enter each of the variable names. This becomes a tedious procedure when the number of variables is very high. Is there an easier way without specificing the variable names?

• What if instead of a, b, c, ... you use indexed variables, e.g., a[1], a[2], a[3], ... ? Apr 15 at 8:32

x = a + a b + a b c + a b c d;

Select[x, Length[#] < 3 &]

(* a + a b *)


or

DeleteCases[x, _?(Length[#] > 2 &)]

(* a + a b *)


or

Total@Cases[x, _?(Length[#] < 3 &)]

(* a + a b *)


Replace your manual selection of variables with an automated selection:

x = a + a b + a b c + a b c d
coeffs = CoefficientRules[x, Variables[x]];
selects = Select[coeffs, Total@(#[[1]]) <= 2 &];
x = FromCoefficientRules[selects, Variables[x]]


You can use Variables to obtain them without manually entering them:

x /. Verbatim[Plus][terms___] :> Plus @@ Pick[{terms}, UnitStep[2 - Length@*Variables /@ {terms}], 1]

• Your answer applied to x = a + a b + a b c + a b c d evaluates 0? Apr 15 at 9:32