Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematica: Determine if all integers in a list are less than a number?

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.

like image 204
Nope Avatar asked Jul 26 '09 16:07

Nope


2 Answers

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.

like image 35
gdelfino Avatar answered Sep 27 '22 20:09

gdelfino


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.

like image 69
Joey Robert Avatar answered Sep 27 '22 22:09

Joey Robert