Compute pairwise element of two 1D array

You can use SciPy’s cdist for that:

import numpy as np
from scipy.spatial.distance import cdist

def diff_len(string1, string2):
    return abs(len(string1) - len(string2))

first = np.array(["hello", "hello", "hellllo"])
second = np.array(["hlo", "halo", "alle"])
d = cdist(first[:, np.newaxis], second[:, np.newaxis], lambda a, b: diff_len(a[0], b[0]))
print(d.T)
# [[2. 2. 4.]
#  [1. 1. 3.]
#  [1. 1. 3.]]

Note that you would need to cast the output matrix type to make it integer though.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top