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

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

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

Thank you for your help.

+5
source share
3 answers

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

+7
source

Before proposing a solution, let me comment on the previous two solutions. Let's call Joey Robert the magicFunction1 solution and Eric's magicFunction2 solution.

magicFunction1 . , , , 10, , . magicFunction2

:

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

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

,

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}

, - magicFunction4, , , magicFunction1. , magicFunction3 magicFunction4.

+6

"Fold":

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

'(# 2 < val)' ('# 2'). , , , , , Max.

"& & # 1 ' .

And "True" is the base register - the result for an empty list.

To find out how this works, you can pass some undefined values ​​and see what the expression expands:

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

Out[10]= c < 10 && b < 10 && a < 10
+3
source

All Articles