I have a list of polynomials polys
linear in a set of variables vars
. How do I partition the list based on successive dependence on vars
?
More concretely, suppose that here is my list of polynomials in three variables:
polys = {x, 2 + x + y + z, y, 2 + x + y, 2 + x, -1 + y, y + z, z};
vars = {x, y, z};
I need a fast, functional way to partition this list, so that the first group depends only on x
, the next group only on x
and y
, the next group only on x
, y
and z
, ... and so on...
Here is my function that does it:
notFreeQ[a_] := Not[FreeQ[#, a]] &
partit[polys_, vars_] :=
Reverse[First@Last@Reap[
Fold[Complement[#1, Sow[Select[#1, notFreeQ[#2]], "selected"]] &,
polys, Reverse[vars]], "selected"]]
partit[polys, vars]
(* {{x, 2 + x}, {-1 + y, y, 2 + x + y}, {2 + x + y + z, y + z, z}} *)
I believe there should be a more efficient functional way of achieving my task. In particular, I do not like how I have to use Sow
/Reap
on the polynomials that satisfy the criteria, only to discard the actual result of the function Fold
. I am also unhappy with using Complement
to select the remaining polynomials since it is inefficient.
Can someone help me do a better job partitioning the list of polynomials?