Skip to content

Semantics, limitations and divergences

A central reference for strsimpy 0.5.0 behavior that differs from TextDistance and other implementations.

Several string measures have more than one accepted definition. Where a choice had to be made, strsimpy 0.5.0 follows the documented definition and the behavior of the upstream Java library where one exists. This page collects the deliberate differences from TextDistance 4.6.2 and other common implementations, together with the edge cases that are easiest to miss.

These are semantics, not accidents. If a score differs from another package, check the definition below before treating it as a bug.

Summary

Measure This library Common alternative Practical effect
Tversky k-shingle sets TextDistance uses multisets Duplicate shingles are counted once here.
Tanimoto Standard set coefficient, equal to Jaccard TextDistance applies log2 No negative similarities and no -inf.
RatcliffObershelp difflib tie-breaking Other libraries may break ties differently Scores can be asymmetric on repeated patterns.
MLIPNS Binary product-name heuristic General-purpose similarities Short strings are deliberately permissive.
StrCmp95 ASCII-only confusion credit Broader phonetic tables Non-ASCII pairs receive no partial credit.
MongeElkan Standard denominator TextDistance divides by the squared first token count Multi-token scores differ.
Alignment classes Raw scores Distance or similarity APIs Scores may be negative and are not normalized.
NormalizedCompressionDistance RLE only zlib, bz2 or lzma compressors Values are compressor-dependent and not always in [0, 1].
Bag Character-multiset distance only Similarity APIs There is no normalized similarity method.

Shingle metrics share one profile definition

QGram, Cosine, Jaccard, SorensenDice, OverlapCoefficient, Tversky and Tanimoto first convert a string to k-shingles. Before shingling, each run of Python whitespace is collapsed to a single ASCII space. The profile then counts every distinct shingle; the set measures discard the counts.

Two consequences follow:

  • Jaccard(3).similarity(" ", " ") is 1.0 because the raw strings are equal, but Jaccard(3).similarity(" ", " ") is 0.0: the strings differ, and neither yields a 3-shingle after normalization.
  • QGram(2).distance("aaaa", "aa") is 2 because the profile counts occurrences, while Jaccard(2).similarity("aaaa", "aa") is 1.0 because both sets are {'aa'}.

NGram is the exception: it compares the raw input and does not normalize whitespace.

Tversky: sets, not multisets

The Tversky index is:

|A intersect B| / (|A intersect B| + alpha * |A - B| + beta * |B - A|)

This implementation converts both inputs to sets of k-shingles. Repeated shingles are counted once. TextDistance uses multisets, so the two libraries disagree on duplicate-heavy inputs such as ("aaa", "aa") with k=2; here the similarity is 1.0.

from strsimpy import Tversky

print(Tversky(1, 1.0, 1.0).similarity("abc", "bcd"))
print(Tversky(1, 1.0, 0.0).similarity("abc", "ab"))
print(Tversky(1, 1.0, 0.0).similarity("ab", "abc"))
0.5
0.6666666666666666
1.0

With alpha = beta = 1.0, the index is the Jaccard index. With alpha = beta = 0.5, it is the Sorensen-Dice coefficient. When alpha != beta the result is asymmetric, and its distance 1 - similarity is asymmetric too.

alpha and beta must be finite, non-negative and not both zero; otherwise the constructor raises ValueError.

Tanimoto: the standard set coefficient

For binary or set vectors, the standard Tanimoto similarity is the Jaccard index:

|A intersect B| / |A union B|

Tanimoto(k) therefore matches Jaccard(k), and its distance is 1 - similarity, which is a metric.

from strsimpy import Tanimoto

tanimoto = Tanimoto(2)
print(tanimoto.similarity("night", "nacht"))
print(tanimoto.distance("night", "nacht"))
0.14285714285714285
0.8571428571428572

TextDistance’s Tanimoto instead returns log2(Jaccard). That produces negative similarities for partial overlap and -inf for disjoint inputs. This library deliberately uses the standard set definition, so its similarity is in [0, 1]. Only the binary/set variant is exposed; the extended real-valued count-vector variant is not implemented.

Ratcliff-Obershelp: difflib tie-breaking

Ratcliff-Obershelp repeatedly finds the longest common substring, counts it, and recurses on the parts to its left and right:

similarity = 2 * matched / (len(s0) + len(s1))
distance   = 1 - similarity

Ties between equally long common substrings are resolved like Python’s difflib: earliest start in the first string, then earliest start in the second. That rule is deterministic but not symmetric, so repeated patterns can produce different scores when the arguments are swapped:

from strsimpy import RatcliffObershelp

print(RatcliffObershelp().similarity("bcd", "aadcbbddd"))
print(RatcliffObershelp().similarity("aadcbbddd", "bcd"))
0.3333333333333333
0.16666666666666666

Other properties:

  • Whitespace is not normalized; spaces count as ordinary characters.
  • It is not a metric, and it can violate symmetry.
  • The worst-case cost is O(m*n*min(m,n)). The implementation uses an explicit stack, so long repetitive inputs do not overflow the call stack.
  • It is the formula behind difflib.SequenceMatcher.ratio(). When comparing against difflib on long inputs, disable its automatic junk heuristic with autojunk=False to avoid differences unrelated to tie-breaking.

MLIPNS: binary and permissive on short strings

MLIPNS is a product-name heuristic, not a general-purpose similarity. It returns exactly 0.0 or 1.0, and distance() is 1 - similarity.

from strsimpy import MLIPNS

print(MLIPNS().similarity("abcg", "abcdeg"))
print(MLIPNS().similarity("abcg", "abcdefg"))
print(MLIPNS().similarity("ab", "cd"))
print(MLIPNS().similarity("abcd", "wxyz"))
1.0
0.0
1.0
0.0

The defaults are threshold=0.25 and max_mismatches=2. The threshold is the maximum mismatch fraction still accepted, and max_mismatches is the number of extra comparison rounds after the first one. A non-finite threshold or one outside [0, 1] raises ValueError.

The measure is deliberately permissive for short inputs: "ab" against "cd" is considered similar. It is not a metric. Use it only when the application is specifically product-name matching.

Strcmp95: ASCII-only confusion credit

Strcmp95 is the US Census Bureau string comparison routine. It is a Jaro-Winkler variant with a phonetic and OCR confusion table.

Before comparing, both inputs are stripped of surrounding Python-style whitespace and uppercased per code point. The result lies in [0, 1], and distance() is 1 - similarity.

from strsimpy import StrCmp95

strcmp = StrCmp95()
print(strcmp.similarity("MARTHA", "MARHTA"))
print(strcmp.similarity("  martha  ", "marhta"))
print(strcmp.similarity("Ä", "A"))
print(strcmp.similarity("O", "0"))
0.9611111111111111
0.9611111111111111
0.0
0.0

Two limits explain the last two values:

  • Confusion-table partial credit is granted only to characters with ASCII code points greater than 0 and less than 91, the range used by the original C implementation. Non-ASCII characters can still match exactly, but never receive partial credit, so "Ä" against "A" scores 0.0.
  • The confusion table applies only when at least one exact match already exists. "O" against "0" scores 0.0 even though the table contains that pair.

Uppercasing uses Rust’s Unicode tables per code point, which can differ from Python’s str.upper() for a handful of exotic code points. Common cases such as ß to SS behave identically. Pass long_strings=True to enable the additional long-string adjustment of the original algorithm.

Monge-Elkan: the standard formula and whitespace tokens

The standard Monge-Elkan similarity is:

ME(A, B) = (1 / |A|) * sum over a in A of max over b in B of sim_inner(a, b)

similarity(s0, s1) splits both inputs with Python str.split() semantics: runs of Unicode whitespace separate tokens; leading and trailing whitespace is ignored. Punctuation and case are preserved. To use custom tokenization, split the text yourself and join the tokens with single spaces before calling.

from strsimpy import MongeElkan

print(MongeElkan().similarity("Niall", "Neal"))
print(MongeElkan().similarity("a b", "b c"))
print(MongeElkan().similarity("a b", "a"))
print(MongeElkan(symmetric=True).similarity("a b", "a"))
0.8049999999999999
0.5
0.5
0.75

The inner similarity is "jaro_winkler" by default; "normalized_levenshtein" is also available. The default direction is asymmetric because the average runs over the first token list. With symmetric=True, the forward and backward scores are averaged.

TextDistance’s multi-token implementation divides the aggregate by the squared first token count rather than by the first token count. That happens to agree for single-token inputs but makes multi-token scores too low. For ("a b", "b c"), the standard score is 0.5; dividing the same aggregate by four gives 0.25.

Both token lists empty yields similarity 1.0; exactly one empty list yields 0.0. These conventions apply in both asymmetric and symmetric mode.

Alignment: raw scores, not distances

NeedlemanWunsch, SmithWaterman and Gotoh expose alignment scores:

  • score(s0, s1) returns a raw float. Scores may be negative.
  • alignment(s0, s1) returns (op, source, target) tuples where op is "match", "substitute", "insert" or "delete"; a gap uses "".

The defaults are match_score=1.0, mismatch_score=-1.0, and gap_cost=1.0 for Needleman-Wunsch and Smith-Waterman. Gotoh uses gap_open=1.0 and gap_extend=0.5.

None of these classes has distance() or similarity(), and none is registered as a StringDistance. Do not compare scores computed with different parameters or interpret them as percentages.

Smith-Waterman returns the maximum cell

Smith-Waterman local alignment ignores unrelated prefixes and suffixes. The score is the maximum cell anywhere in the dynamic-programming matrix, not the bottom-right cell, and is therefore always non-negative.

from strsimpy import SmithWaterman

print(SmithWaterman().score("AGACTAGTTAC", "CGAGACGT"))
print(SmithWaterman().score("abc", "xyz"))
4.0
0.0

Some reference implementations, including TextDistance, return the bottom-right cell instead and report 1.0 for the first pair. This library reports the correct local-alignment score, 4.0. When no positive-scoring local alignment exists, the score is 0.0 and alignment() returns an empty list.

Gotoh: empty inputs and gap_extend=0

Gotoh uses an affine gap penalty: a gap run of length L costs gap_open + (L - 1) * gap_extend. Empty strings are handled explicitly, so the non-empty input becomes a single gap run:

from strsimpy import Gotoh, NeedlemanWunsch

print(Gotoh().score("", "abc"))
print(Gotoh(gap_open=1.0, gap_extend=0.0).score("a", "aaaa"))
print(NeedlemanWunsch(gap_cost=1.0).score("a", "aaaa"))
-2.0
0.0
-2.0

TextDistance raises IndexError for Gotoh with an empty input; this library does not. Setting gap_extend=0 does not reduce Gotoh to Needleman-Wunsch’s linear gap: a whole gap run then costs gap_open once, while a linear alignment charges gap_cost per gap character. In the second example above, Gotoh pays one match and one gap run for 0.0; Needleman-Wunsch pays one match and three gap columns for -2.0. With these parameters, the two models agree only when every gap run has length one.

alignment() emits one operation per gap character; consecutive insertions or deletions are not grouped into gap runs. Ties are resolved deterministically: Needleman-Wunsch prefers the diagonal, then deletion, then insertion; Smith-Waterman starts at the first maximum cell in row-major order; Gotoh prefers the paired state, then a gap in the target, then a gap in the source. Other libraries may choose a different optimal alignment with the same score.

Normalized compression distance: RLE only

NCD compares compressed sizes:

NCD(s0, s1) = (C(s0 + s1) - min(C(s0), C(s1))) / max(C(s0), C(s1))

Both concatenation orders are evaluated and the smaller compressed size is used, so the result is symmetric by construction. If both compressed sizes are zero (both inputs are empty), the distance is 0.0.

from strsimpy import NormalizedCompressionDistance

ncd = NormalizedCompressionDistance()
print(ncd.distance("aaaa", "aaab"))
print(ncd.distance("abc", "abc"))
print(ncd.distance("aaa", "aaa"))
print(ncd.distance("", "abc"))
0.3333333333333333
1.0
0.0
1.0

The implementation limitations are important:

  • Only the "rle" compressor is shipped. zlib, bz2 and lzma are not available; an unknown compressor name raises ValueError.
  • Values are compressor-dependent. Identical strings are not guaranteed to score 0: RLE gives 1.0 for "abc" against "abc" but 0.0 for "aaa" against "aaa".
  • Values are not guaranteed to lie in [0, 1].
  • RLE operates on Unicode code points and measures the compressed size in characters, not bytes. A run of more than two equal characters is encoded as the decimal digits of its length followed by the character ("3a"); runs of one or two characters are emitted unchanged.
  • Only distance() is provided. The class is not registered as a StringDistance.

Bag: a character-multiset distance only

Bag distance is the larger multiset difference between the character bags of two strings:

Bag(A, B) = max(|A - B|, |B - A|)
          = max(len(s0), len(s1)) - |A intersect B|

It is symmetric, satisfies the triangle inequality, and is a metric. Character order and position are ignored, so anagrams have distance 0.

from strsimpy import Bag

print(Bag().distance("qwe", "ewq"))
print(Bag().distance("qwe", "rtys"))
print(Bag().distance("", "abc"))
0
4
3

Bag provides only distance(). It has no similarity() and no normalized form; divide by max(len(s0), len(s1)) when the longer string is non-empty if you need a value in [0, 1]. It operates on characters rather than words and does not normalize whitespace.

Documentation access on this static site

This Nimbus documentation site is deployed as static assets on GitHub Pages. There is no request-time server, so the site does not perform server-side Markdown negotiation for browsers or agents and does not expose a remote MCP endpoint. The alternate representations are still published as static files: each page has a direct index.md rendering and an authored index.mdx source, and the site-level llms.txt (plus the section-level files and llms-full.txt) remains available for agents that prefer plain text.

  • Choosing an algorithm for a task-first comparison of normalized, raw, metric and non-metric measures.
  • Performance for complexity, memory and code-point semantics.
  • API reference for constructors, return types, ABC registrations and pickling.

Type to search…

↑↓ navigate↵ selectEsc close