5
$\begingroup$

I'd like to return a a boolean variable that tells me whether numbers in a list are mostly positive. For example:

a = {3,2,3,4,-1,-2,-5,3} 

There are 5 positive values and 3 negative ones in list a. That is, 5/8 of the values (more than 50% of them) are positive. How do I get a boolean variable that tells me if this is true or not.

$\endgroup$
  • 5
    $\begingroup$ mostlyPos[a_?VectorQ] := (Count[a, _?Positive]/Length[a]) > 1/2; $\endgroup$ – Bob Hanlon Dec 2 '19 at 16:55
  • 2
    $\begingroup$ Or mostlyPos[a_?VectorQ] := Mean[Unitstep[a-1]]>1/2 (works only for vectors of integers). $\endgroup$ – Henrik Schumacher Dec 2 '19 at 18:50
8
$\begingroup$

My favorite way, out of many possibilities:

Majority @@ Positive[{3, 2, 3, 4, -1, -2, -5, 3}]
   True

Majority @@ Positive[{-100, -200, -300, 10, 1000000}]
   False

(Change Positive[] to NonNegative[] if wanted.)

|improve this answer|||||
$\endgroup$
5
$\begingroup$

Here is one way:

mp[l_] := Total[Sign[l]] > 0

mp[a]
(* True *)

mp[{0, 0, 0}]
(* False *)

mp[{-100, -200, -300, 10, 1000000}]
(* False *)

As written, mp uses a strictly positive test. If desired, we can relax that by changing the test from ... > 0 to ... >= 0 in which case zeroes and equal counts of positives and negatives will be treated as "mostly positive".

|improve this answer|||||
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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