I already import this
from functools import reduce
import operator
when i try this
>>> print(reduce(operator.or_, \[2,4,5]))
7
>>> print(reduce(operator.or_, \[2,4,6]))
6
>>> print(reduce(operator.or_, \[2,3,6]))
7
>>> print(reduce(operator.or_, \[2,3,8]))
8
I'm pretty confused, i dont know how does exactly it work ?
CodePudding user response:
Reduce applies the bitwise OR operator to each successive pair of elements in the input array. For example in your first case, it starts with 2 and 4. Bitwise OR on 2 (010 in binary) and 4 (100) gives 6 (110). The bitwise OR is then applied to 6 i.e. result of computation and 5 (101) i.e. the next element in the array, resulting in 7 (111). Similarly for the rest.
CodePudding user response:
operator.or_
is a bitwise operation, so
reduce(operator.or_, [2,4,5])
is
2 | 4 | 5
which is
2 = 010
4 = 100
5 = 101
-------
7 = 111
Unfortunately, there's no equivalent of or
in operator
module, so:
>>> reduce(lambda a, b: a or b, [2,4,5])
2