我有两个列表l1
并l2
包含可能具有不同长度的整数,我想在这两个向量之间的每个可能配对之间执行计算。
具体来说,我正在检查每对之间的汉明距离,如果距离足够小,我想“计算”它。
天真地,这可以实现
def hamming_distance(n1: int, n2: int) -> float:
return bin(n1 ^ n2).count('1')/32.0
matches = 0
for n1 in l1:
for n2 in l2:
sim = 1 - hamming_distance(n1, n2)
if sim >= threshold:
matches += 1
但这不是很快。
我没有成功尝试利用scipy.spatial.distance.cdist
,我认为我将首先计算所有对之间的汉明距离,因为scipy.spatial.cdist 文档指出它将
计算两个输入集合中每对之间的距离。
然后计算满足谓词的元素个数,即汉明距离1 - d >= threshold
在哪里d
,即
from scipy.spatial.distance import cdist
l1 = l1.reshape(-1, 2) # After np.array
l2 = l2.reshape(-1, 2)
r = cdist(l1, l2, 'hamming')
matches = np.count_nonzero(1 - r >= threshold)
但是各个解决方案找到的匹配数不同。我注意到可以cdist
使用函数进行调用,cdist(XA, XB, f)
但是我没有成功编写我的实现hamming_distance
以使其正确广播。
我已经查看了这个问题/答案,但它假定两个列表的长度相同,这不是这里的情况。