Skip to content

fix: prevent ZeroDivisionError in token-based algorithms for short sequences - #97

Open
gaoflow wants to merge 1 commit into
life4:masterfrom
gaoflow:fix-qval-zero-division
Open

fix: prevent ZeroDivisionError in token-based algorithms for short sequences#97
gaoflow wants to merge 1 commit into
life4:masterfrom
gaoflow:fix-qval-zero-division

Conversation

@gaoflow

@gaoflow gaoflow commented Jun 24, 2026

Copy link
Copy Markdown

When qval > 1 and an input sequence has fewer characters
than qval, find_ngrams() returns an empty list. Token-based
similarity algorithms (Jaccard, Sorensen, Overlap, Cosine,
Tversky) crash with ZeroDivisionError because the empty
n-gram lists produce zero denominators.

Fix (+1 char): find_ngrams(s, self.qval) or list(s)
when n-gram extraction yields nothing for a non-empty sequence,
fall back to individual characters. This preserves the intended
semantics: short strings are compared by their constituent
characters instead of being silently treated as empty.

Reproduction:

td.Jaccard(qval=2)("a", "ab")  # ZeroDivisionError
td.Sorensen(qval=2)("a", "ab")  # ZeroDivisionError

404/404 tests pass (26 hypothesis deadline flakes pre-existing).

This pull request was prepared with the assistance of AI, under my
direction and review.

…rter than qval

When qval > 1 and the input sequence is shorter than qval characters,
find_ngrams returns an empty list, causing _get_sequences to produce
empty sequences. Token-based algorithms (Jaccard, Sorensen, Overlap,
Cosine, Tversky) then divide by zero when computing
intersection/denominator.

Fall back to individual characters via list(s) when n-gram extraction
yields no n-grams, preserving the information in the input sequence
rather than silently treating it as empty.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant