Skip to content

Instantly share code, notes, and snippets.

@Jiler01
Created December 10, 2023 15:16
Show Gist options
  • Save Jiler01/fd8ecabd397761e9d52ff044f1014d63 to your computer and use it in GitHub Desktop.
Save Jiler01/fd8ecabd397761e9d52ff044f1014d63 to your computer and use it in GitHub Desktop.
Some easy-to-use best matches seeker using linear search (possible improvements on the sorting loop
def matches(target: str, data: str, cutoff: float):
if len(target) == 0:
raise ZeroDivisionError("Data must be at leat one character long")
score = 0.0
for target_letter_index in range(len(target)):
if target[target_letter_index] in data:
score += .5
if target_letter_index < len(data) and data[target_letter_index] == target[target_letter_index]:
score += .5
score /= len(target)
return score >= cutoff, score
def close_matches(target: str, data: list, cutoff: float = 0.5, amount: int = 5, function=lambda x: x):
found = []
for reading in data:
reading_passes, reading_affinity = matches(target.lower(),
function(reading).lower(), cutoff=cutoff)
if reading_passes:
insert_index = len(found)
finished = False
i = 0
while i < len(found) and not finished:
if found[i][1] < reading_affinity:
insert_index = i
finished = True
else:
i += 1
found.insert(insert_index, (reading, reading_affinity))
return found[:amount]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment