question about sublist



On Tue, Apr 17, 2007 at 03:10:02PM +0100, Jaime E. Villate wrote:
> On Tue, 2007-04-17 at 02:42 -0400, sen1 at math.msu.edu wrote:
> >   I have a large list of floating point numbers.
> > 
> > Does anyone have a clever predicate to sublist which will extract the
> >   elements whose immediate successors have the same sign? 
> here is an idea:
> 
> (%i1) sublist(x):= block([l: [], prev: x[1]], for i:2 thru length(x) do
>         (if prev*x[i] > 0 then l: cons(prev,l), prev:x[i]), reverse(l));
> (%i2) a: [2,3,-3,-2,-1, 0, 5, 7]$
> (%i3) sublist(a);
> (%o5) [2, - 3, - 2, 5]

The only suggestion I have is that x[i] is linear in the length of the
list. Since you execute it once per list element, the entire loop is
quadratic time. The fastest way to execute this type of loop is to
keep two variables which store the first and the second element, and
then to step them through the list at each iteration until the second
one steps off the list.

It's irrelevant for a one-off loop on a medium sized list, but it's
essential in a larger computation because it will be significantly
faster.

-- 
Daniel Lakeland
dlakelan at street-artists.org
http://www.street-artists.org/~dlakelan