Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 2024-05-18 - [Optimize SequenceMatcher in O(N^2) loops]
**Learning:** `difflib.SequenceMatcher(None, a, b).ratio()` creates a new object and computes the expensive longest common subsequence algorithm each time. In an O(N^2) similarity deduplication pass, this is a significant bottleneck.
**Action:** When comparing a string `b` against many strings `a` in a loop, reuse `matcher = SequenceMatcher(b=title)`. In the inner loop, use `matcher.set_seq1(seen)`, and check `matcher.real_quick_ratio()` and `matcher.quick_ratio()` upper bounds before calling `ratio()` to exit early for dissimilar strings.
7 changes: 6 additions & 1 deletion src/county_research_ai/processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,15 @@ def deduplicate(self, docs: list[RawDoc]) -> list[RawDoc]:
for doc in url_deduped:
title = doc.title.strip()
if not title:
title_deduped.append(doc)
continue
is_dup = False

# 性能优化: 复用 SequenceMatcher 并通过 real_quick_ratio 快速剪枝 O(N^2) 耗时
matcher = SequenceMatcher(b=title)
for seen in seen_titles:
if SequenceMatcher(None, title, seen).ratio() > 0.85:
matcher.set_seq1(seen)
if matcher.real_quick_ratio() > 0.85 and matcher.quick_ratio() > 0.85 and matcher.ratio() > 0.85:
is_dup = True
break
if not is_dup:
Expand Down
Loading