【问题标题】:reduce time-complexity of nested loop in python减少python中嵌套循环的时间复杂度
【发布时间】:2020-08-13 05:15:37
【问题描述】:

这是我的代码。需要 17 小时才能完成。您能否建议任何替代代码以减少计算时间?

# test algorithm1 - fuzzy
matched_pair = []
for x in dataset1['full_name_eng']:
    for y in dataset2['name']:
        if (fuzz.token_sort_ratio(x,y) > 85):
            matched_pair.append((x,y))
            print((x,y))

我尝试了不同的但没有工作((。

dataset1 - 10krows, dataset2 - 1M 行, fuzz.token_sort_ratio(x,y) - 是一个接受 2 个参数(2 个字符串)并输出整数的函数 - 这 2 个字符串的相似度

【问题讨论】:

  • 你能提供更多细节吗?什么是数据集1?那有多大?你可以发布样本数据吗?什么是绒毛?
  • 拆分列表并并行处理
  • 请参阅How to Askhelp center
  • 请看我编辑过的问题 - 添加了一些细节
  • 您可以查看局部敏感散列 (LSH) 以实现更快的相似字符串搜索。 Here is an article explaining it

标签: python time-complexity


【解决方案1】:

由于这里没有真正使用数据框,我将简单地使用以下两个列表:

import string
import random

random.seed(18)
dataset1 = [''.join(random.choice(string.ascii_lowercase + ' ') for _ in range(random.randint(13, 20))) for s in range(1000)]
dataset2 = [''.join(random.choice(string.ascii_lowercase + ' ') for _ in range(random.randint(13, 20))) for s in range(1000)]

将这两个列表与您使用fuzzywuzzy 提供的代码一起使用。作为第一个更改,您可以使用RapidFuzz(我是作者),它基本上与 FuzzyWuzzy 相同,但速度要快得多。当使用我的测试列表时,这大约是您的代码的 7 倍。另一个问题是,当使用 fuzz.token_sort_ratio 时,字符串总是小写的,例如标点符号被删除。虽然这对字符串匹配有意义,但您对列表中的每个字符串都执行多次,这在处理更大的列表时会累加。在这些列表中,仅使用一次 RapidFuzz 和预处理的速度大约是这些列表的 14 倍。

from rapidfuzz import fuzz, utils

dataset2_processed = [utils.default_process(x) for x in dataset2]
dataset1_processed = [utils.default_process(x) for x in dataset1]

matched_pair = []
for word1, word1_processed in zip(dataset1, dataset1_processed):
    for word2, word2_processed in zip(dataset2, dataset2_processed):
        if fuzz.token_sort_ratio(word1_processed, word2_processed, processor=None, score_cutoff=85):
            matched_pair.append((word1, word2))

【讨论】:

  • 谢谢!算法较弱,但速度快 5 倍!
猜你喜欢
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
相关资源
最近更新 更多