Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading