【发布时间】:2021-02-13 03:10:22
【问题描述】:
我正在使用来自 textdistance 库 (https://github.com/life4/textdistance) 的 textdistance.needleman_wunsch.normalized_distance。我将它与来自Scipy 库的cdist 一起使用来计算序列的对距离。但是由于嵌套的枚举for循环,这个过程很长。
在这里您可以找到 textdistance 库中使用的代码,这需要时间,我想知道您是否知道如何加快嵌套的 for 循环,也许使用列表理解?
s1 = "sentence1"
s2 = "sentevfers2"
gap = 1
def sim_func(*elements):
"""Return True if all sequences are equal.
"""
try:
# for hashable elements
return len(set(elements)) == 1
except TypeError:
# for unhashable elements
for e1, e2 in zip(elements, elements[1:]):
if e1 != e2:
return False
return True
dist_mat = numpy.zeros(
(len(s1) + 1, len(s2) + 1),
dtype=numpy.float,
)
# DP initialization
for i in range(len(s1) + 1):
dist_mat[i, 0] = -(i * gap)
# DP initialization
for j in range(len(s2) + 1):
dist_mat[0, j] = -(j * gap)
""" Possible enhancement with list comprehension ? """
# Needleman-Wunsch DP calculation
for i, c1 in enumerate(s1, 1):
for j, c2 in enumerate(s2, 1):
match = dist_mat[i - 1, j - 1] + sim_func(c1, c2)
delete = dist_mat[i - 1, j] - gap
insert = dist_mat[i, j - 1] - gap
dist_mat[i, j] = max(match, delete, insert)
distance = dist_mat[dist_mat.shape[0] - 1, dist_mat.shape[1] - 1]
print(distance)
【问题讨论】:
-
该嵌套循环不会累积第三个列表,因此理解并不适合直接翻译。您也许可以使用理解来创建
match、delete、insert三元组的列表,然后遍历这些元组,但我看不出有什么更好的。
标签: python performance list-comprehension nested-loops