Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #6097

Re: efficiently testing a list

From "Oleksandr Rasputinov" <oleksandr_rasputinov@hmamail.com>
Newsgroups comp.soft-sys.math.mathematica
Subject Re: efficiently testing a list
Date 2011-11-01 05:09 +0000
Organization Steven M. Christensen and Associates, Inc and MathTensor, Inc.
Message-ID <j8nuti$ehp$1@smc.vnet.net> (permalink)
References <j8j5o2$fab$1@smc.vnet.net>

Show all headers | View raw


On Sun, 30 Oct 2011 09:34:58 -0000, zb <zaeem.burq@gmail.com> wrote:

> Consider the list of pairs:
>
> List = Table[ {a[i],b[i]} , {i,1,N} ].
>
> or
>
> List = { {a[1],b[1]} , {a[2],b[2]} , {a[3],b[3]} , ... ,
> {a[N],b[N]} },
>
> and a given function f[a].
>
> What is the quickest way of testing if all elements of List satisfy
> f[a[i]] < b[i].
>

While slightly more obscure than the suggestions already given, the  
following implements short-circuit evaluation:

LengthWhile[data, f[#[[1]]] < #[[2]] &] == Length[data]

This can be faster if the condition is violated somewhere near the  
beginning of a long list:

data = RandomInteger[{1, 100}, {1*^6, 2}];
f[x_] := 1/x;

Timing[
  LengthWhile[data, f[#[[1]]] < #[[2]] &] == Length[data]
]

{0.141, False}

Timing[
  (* Bob Hanlon's suggestion *)
  And @@ (f[#[[1]]] < #[[2]] & /@ data)
]

{4.031, False}

On the other hand, if the condition never fails, it will be slower:

data = RandomInteger[{2, 100}, {1*^6, 2}];
f[x_] := 1/x;

Timing[
  LengthWhile[data, f[#[[1]]] < #[[2]] &] == Length[data]
]

{6.016, True}

Timing[
  (* Bob Hanlon's suggestion *)
  And @@ (f[#[[1]]] < #[[2]] & /@ data)
]

{4.141, True}

So, given these choices, there is no absolute quickest method. Which is  
faster in practice will depend on the properties of your list.

Back to comp.soft-sys.math.mathematica | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

efficiently testing a list zb <zaeem.burq@gmail.com> - 2011-10-30 09:34 +0000
  Re: efficiently testing a list "Oleksandr Rasputinov" <oleksandr_rasputinov@hmamail.com> - 2011-11-01 05:09 +0000
  Re: efficiently testing a list Ray Koopman <koopman@sfu.ca> - 2011-11-02 07:05 +0000

csiph-web