Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find different pair in a list by python

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.

like image 589
vincentlai Avatar asked Jul 16 '18 05:07

vincentlai


People also ask

How do you find unique pairs in Python?

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.

What is pair () in Python?

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.


2 Answers

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])
like image 87
Joe Avatar answered Oct 09 '22 03:10

Joe


Vectorized Comparison

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)]

like image 36
cs95 Avatar answered Oct 09 '22 04:10

cs95