I am trying to apply a method that takes in two vectors and returns a resulting vector.
Below is an example input and expected result. Valid values are 0, 1, and -1:
a = [ 1, 0, -1, 0, 0, 1]
b = [ 0, 0, -1, 0, 1, -1]
result = my_func(a, b)
# [ 1, 0, -1, 0, 1, 0]
I am trying to apply the following logic to get a resulting vector. For each index of both vector:
- If either a[i] or b[i] is zero and the other is either
-1
or1
, set result[i] as the non-zero value. - If both are the same value, set result[i] as the shared value.
- If a[i] and b[i] are (1, -1) or (-1, 1) respectively, set result[i] as zero.
My intial intuition is that a bitwise logic would be able to meet the above specifications, but I haven't been able to solve it so far:
np.bitwise_or(a,b)
# array([ 1, 0, -1, 0, 1, -1])
np.bitwise_and(a,b)
# array([ 0, 0, -1, 0, 0, 1])
np.bitwise_xor(a,b)
# array([ 1, 0, 0, 0, 1, -2])
If a logical pairing is not possible, would the most efficient method of meeting the specification be applying a lambda to each index?
CodePudding user response:
Code used to run the benchmark
perfplot.show(
setup = lambda n: (np.random.choice([1, 0, -1], n).astype(np.int8),
np.random.choice([1, 0, -1], n).astype(np.int8)),
kernels = [lambda a, b: (a | b) * (-a ^ b).view('bool'),
lambda a, b: np.clip(a b, -1, 1)],
labels=['or and multiply xor', 'add and clip'],
n_range=[2**k for k in range(10,25,2)],
equality_check=np.array_equal
)