Skip to content

Instantly share code, notes, and snippets.

@ducnh1022
Created March 5, 2026 17:47
Show Gist options
  • Select an option

  • Save ducnh1022/606a1821836e14de6555dda98a31bf9c to your computer and use it in GitHub Desktop.

Select an option

Save ducnh1022/606a1821836e14de6555dda98a31bf9c to your computer and use it in GitHub Desktop.
import difflib
def fuzzy_insert(words, new_word, threshold=0.6):
# 1️⃣ Calculate similarity scores
similarities = [
(i, difflib.SequenceMatcher(None, new_word, w).ratio())
for i, w in enumerate(words)
]
# 2️⃣ Find best match
best_index, best_score = max(similarities, key=lambda x: x[1])
# 3️⃣ If similarity too low → append to end
if best_score < threshold:
words.append(new_word)
return words
# 4️⃣ Insert near best match (keep local alphabetical order)
insert_index = best_index
# If new word should come after best match alphabetically
if new_word > words[best_index]:
insert_index = best_index + 1
words.insert(insert_index, new_word)
return words
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment