# Collect function with iterator issue

I've got the following code for the first few terms of an expansion. I want to collect the terms in increasing powers of (s/r) but using an iterator. The code is as follows:

formula=1-n x + 1/2 n (n+1) x^2-1/6 n (n+1 ) (n+2) x^3 /. {x->((s/r)^2-2 (s/r) Cos[θ]),
n->1/2};
Expand[%];
Collect[%,{(s/r),(s/r)^2,(s/r)^3,(s/r)^4}]


The output is what I want but how would I do this using a counter or iterator? So something like

Collect[%, {(s/r)^i,{i,0,n}}]


But obviously not that because it doesn't work!

• Could you just preinitialize your list of factors? E.g. Collect[Expand[formula], Table[(s/r)^i, {i, 5}]] – b3m2a1 Mar 9 '17 at 1:44
• Excellent job. I had tried something almost the same but your has worked a treat! If you want to write it as an answer I shall kindly accept! – Rumplestillskin Mar 9 '17 at 1:54

We can pre-initialize our list of factors with Table:

Collect[Expand[formula], Table[(s/r)^i, {i, 5}]]

should get the job done.

Or, as Bob Hanlon notes, Power is Listable so we can do:

Collect[Expand[formula], (s/r)^Range[5]]

• Ah very nice. Didn't know Power was Listable. – b3m2a1 Mar 9 '17 at 3:16

Instead of Collect, you can use PolynomialReduce

Flatten@PolynomialReduce[formula, Table[(s/r)^i, {i, n /. n -> 5}], {s, r}][[2]]