I have a list and I want to find different pair in list. I implement a function --> different()
import numpy as np
def different(array):
res = []
for (x1, y1), (x2, y2) in array:
if (x1, y1) != (x2, y2):
res.append([(x1, y1), (x2, y2)])
return res
a = np.array([[[1, 2], [3, 4]],
[[1, 2], [1, 2]],
[[7, 9], [6, 3]],
[[3, 3], [3, 3]]])
out = different(a) # get [[(1, 2), (3, 4)],
# [(7, 9), (6, 3)]]
Is there any other better way to do it? I want to improve my function different. List size may be greater than 100,000.
Given a list of integers and a positive integer k, write a Python program to count all distinct pairs with difference equal to k. We will use list comprehension using two loops using 'e1' and 'e2' that will traverse given list. We check if e1-e2 == k or not and return the (e1, e2) tuple respectively.
Pairing functions take two integers and give you one integer in return. What makes a pairing function special is that it is invertable; You can reliably depair the same integer value back into it's two original values in the original order.
The numpy way to do it is
import numpy as np
a = np.array([[[1, 2], [3, 4]],
[[1, 2], [1, 2]],
[[7, 9], [6, 3]],
[[3, 3], [3, 3]]])
b = np.logical_or(a[:,0,0] != a[:,1,0], a[:,0,1] != a[:,1,1])
print(a[b])
a[~(a[:, 0] == a[:, 1]).all(1)]
array([[[1, 2],
[3, 4]],
[[7, 9],
[6, 3]]])
This works by taking the first pair of each subarray and comparing each one with the second pair. All subarrays for which entries which are not identical only are selected. Consider,
a[:, 0] == a[:, 1]
array([[False, False],
[ True, True],
[False, False],
[ True, True]])
From this, we want those rows which do not have True at each column. So, on this result, use all
and then negate the result.
~(a[:, 0] == a[:, 1]).all(1)
array([ True, False, True, False])
This gives you a mask you can then use to select subarrays from a
.
np.logical_or.reduce
Similar to the first option above, but approaches this problem from the other end (see DeMorgan's Law).
a[np.logical_or.reduce(a[:, 0] != a[:, 1], axis=1)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With