views:

261

answers:

3

Is there a way in Mathematica to determine if all the integers in a list are less than a set number. For example if I want to know if all the numbers in a list are less than 10:

theList = {1, 2, 3, 10};
magicFunction[theList, 10]; --> returns False

Thanks for your help.

+7  A: 

Look into the Max function for lists, which returns the largest number in the list. From there, you can check if this value is less than a certain number.

Joey Robert
Thanks, good idea.
Casey
Just to spell it out: `magicFunction[lst_, val_] := Max[lst]<val`
dreeves
+3  A: 

This kind of test is easy to construct using 'Fold':

magicFunction[ lst_, val_ ] :=
 Fold[ ((#2 < val) && #1) &, True, lst ]

The phrase '(#2 < val)' is the test of each list element ('#2'). You could put any test you wanted here, so you can do more powerful tests than you can with a listable function like Max.

The ' && #1' then combines the result for your current element with the result for all prior elements.

And 'True' is the base case -- the result for an empty list.

To see how it works, you can pass in some undefined values and see what the expression expands to:

In[10]:= magicFunction[ {a, b, c}, 10 ]

Out[10]= c < 10 && b < 10 && a < 10
Eric
+6  A: 

Before offering my solution let me comment the previous two solutions. Lets call Joey Robert's solution magicFunction1 and Eric's solution magicFunction2.

magicFunction1 is very short and elegant. What I don't like about it is that if I have an very large list of numbers and the first one is already bigger than 10 it still will do all the work of figuring out the largest number which is not needed. This also applies to magicFunction2

I developed the following two solutions:

magicFunction3[lst_, val_] := 
 Position[# < val & /@ lst, False, 1, 1] == {}

and

magicFunction4[lst_, val_] := 
 Cases[lst, x_ /; x >= val, 1, 1] == {}

Doing a benchmark I found

In[1]:= data = Table[RandomInteger[{1, 10}], {10000000}];

In[2]:= Timing[magicFunction1[data, 10]]
Out[2]= {0.017551, False}

In[2]:= Timing[magicFunction2[data, 10]]
Out[2]= {10.0173, False}

In[2]:= Timing[magicFunction3[data, 10]]
Out[2]= {7.10192, False}

In[2]:= Timing[magicFunction4[data, 10]]
Out[2]= {0.402562, False}

So my best answer is magicFunction4, but I still don't know why it is slower than magicFunction1. I also ignore why there is such a large performance difference between magicFunction3 and magicFunction4.

gdelfino
timing of Max and your magicFunction4 could be due to Max being a builtin....i'm not really sure though
Casey
extra plus for actually measuring
nes1983