Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't understand why (5 | -2) > 0 is False where (5 or -2) > 0 is True [duplicate]

This is a pretty trivial question that I haven't been able to find the answer to.

Here is the problem. I have the following array:

vals = [-5, 2]

And I want to check whether val[0] or val[1] is greater than 0. If either is true, then I should output True.

My immediate thought was to use; (vals[1] or vals[0]) > 0) but I'm finding that (5 | -2) > 0 is False where (5 or -2) > 0 is True

Any clarification would be much appreciated.

like image 917
madsthaks Avatar asked Mar 18 '19 15:03

madsthaks


2 Answers

What is the difference between or and |?

or is a logical or and | is a bitwise or logical inclusive or.

The logical or

The logical or in python returns the first value that is true.

Example:

>>> None or False or 5
5
>>> -5 or 2
-5

The bitwise or logical inclusive or

The bitwise or logical inclusive or is represented by the | operator in python and creates a number where all bits are set that are set in at least one of the given numbers.

Example:

  • 2 is in binary 0010
  • 4 is in binary 0100

A logical or between the two results in 0110 which is 6.

>>> 2 | 4
6

How a negative number is stored is generally implementation specific. However on most systems a negative number is stored by creating the two's complement of the positive number by inverting each bit and adding 1.

That number in bitwise ore two any other number still results in a negative number:

>>> -5 | 2
-5

Neither of the two solves your problem

While using

(vals[1] or vals[0]) > 0

seems to work, it fails when you flip the values:

>>> vals = [2, -5]
>>> (vals[1] or vals[0]) > 0
False

You should check both values seperatly

>>> vals = [-5, 2]
>>> vals[0] > 0 or vals[1] > 0
True

For a larger input this may be inconvenient. You should use any with a generator expression:

>>> any(x > 0 for x in vals)
True
like image 79
kalehmann Avatar answered Oct 30 '22 11:10

kalehmann


You want the any function:

>>> any(x > 0 for x in vals)

x | y computes the bitwise OR of the two values, while x or y evaluates to the first "truthy" value. In both cases, the result is then compared to 0: (x or y) > 0 and (x | y) > 0.

What you want to compare each value to zero (as necessary), with

vals[0] > 0 or vals[1] > 0

If you had three values, you'd write

vals[0] > 0 or vals[1] > 0 or vals[2] > 0

The any function generalizes this to a list of any size, without the need to decide how many terms to or together based on the size of the list.

like image 43
chepner Avatar answered Oct 30 '22 09:10

chepner