How to fix list comprehension 'bitwise_and' error and optimize for-loop?

I have the following for loop below, but I want to make this into a more computationally efficient variant. I thought I could do that with list comprehension, but this is giving me the following error: TypeError: ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

EDIT I: I am trying to compare input1 and input2 and if input1 is larger than than input2, then the difference should be squared and scaled by the scaler. Otherwise, a value of zero should be assigned to the output.

How can I fix this and are there any other way to speed this up even more?

# Input variables
input1 = np.array([0.5, 1, 3, 7, 10])
input2 = np.array([0.5, 1.5, 2, 7, 8])
scaler = 3

# For loop
output = np.zeros(len(input1))
for i in range(len(input1)):
    if input1[i] > input2[i]:
        output[i] = scaler * (input1[i] - input2[i])**2  
    else: 
        output[i] = 0      

# List comprehension attempt, but gives error.
output = [scaler * (input1-input2)**2 for i in input1 & input2 if input1 > input2]  

>Solution :

If you are only trying to optimise the for loop with a list comprehension, the following is equivalent:

# Input variables
input1 = np.array([0.5, 1, 3, 7, 10])
input2 = np.array([0.5, 1.5, 2, 7, 8])
scaler = 3

# List comprehension
output = [scaler * (x-y)**2 if x>y else 0 for (x,y) in zip(input1,input2)]

EDIT: This is probably faster as numpy can vectorise the operation

# Input variables
input1 = np.array([0.5, 1, 3, 7, 10])
input2 = np.array([0.5, 1.5, 2, 7, 8])
scaler = 3

# numpy operations
arr = input1-input2
arr = arr.clip(min=0)
output = scaler * arr ** 2

Leave a Reply