3
$\begingroup$

I have a list and a If-statement:

a = {-3, 0, 5};
If[a[[1]] > 1 || a[[2]] > 1 || a[[3]] > 1 , 1, 0]

Output: 1

Is there a way to write the condition shorter? If the list is longer, the condition will get very long.

Or probably more general: Is there a way to create a function which would take the elements of a list and connect them with an operation?

$\endgroup$
2
  • 4
    $\begingroup$ If[AnyTrue[a, # > 1 &], 1, 0] or If[Or @@ Thread[a > 1], 1, 0] is your after? $\endgroup$
    – yode
    Commented Apr 18, 2017 at 2:10
  • 1
    $\begingroup$ Count[a, _?(# > 1 &)] // Unitize $\endgroup$
    – Bob Hanlon
    Commented Apr 18, 2017 at 6:24

2 Answers 2

4
$\begingroup$

If you have a very long list and want to check if any of the elements is larger than one, the fastest way is probably a vectorized operation such as

If[Times @@ UnitStep[1 - a] == 0, 1, 0]
$\endgroup$
2
$\begingroup$

For the particular question:

If[Or @@ (# > 1& /@ a), 1, 0]

but there is a problem you should be aware of: Or returns immediately after a True clause, so if your list is $10^{10}$ long, the version I wrote will take time proportional to $10^{10}$ even if the first comparison returns True.

For general functions, the answer is similar.

$\endgroup$
2
  • $\begingroup$ Is there a way to apply this on two lists, not by checking the whole lists separate, but by checking if the first, second,... last element of both lists is greater than 1? For example: a = {2, 0, 2}; b = {0, 2, 2}; should output 1 because the last element of both lists is greater than 1. But a = {2, 0, 2}; b = {0, 2, 0}; should output 0, because there are no element pairs which are greater than 1. In the end, I want to check for different conditions in the two lists. Like: If a[[1]] > 1 and b[[1]] == 1 OR a[[2]] > 1 and b[[2]] == 1 OR ... and so on. $\endgroup$
    – drcyberz
    Commented Apr 18, 2017 at 11:27
  • $\begingroup$ Can you help me regarding the post above? I want to check for two different conditions in two long lists. If[a[[1]] > 1 && b[[1]] == 1 || a[[2]] > 1 && b[[2]] == 1 || a[[3]] > 1 && b[[3]] == 1, 1, 0] $\endgroup$
    – drcyberz
    Commented Apr 19, 2017 at 21:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.