Skip to content

Sequence similarity algorithms

Jaro-Winkler, longest common subsequence, Metric LCS, and Ratcliff-Obershelp similarity in strsimpy 0.5.0.

Sequence similarity algorithms compare the characters of two strings rather than counting a fixed set of edits. This page covers the four sequence-based calculators in strsimpy 0.5.0. All classes can be imported from the package root, and the historical per-module imports also work.

All algorithms operate on Unicode code points, matching Python’s len() and indexing semantics.

Overview

Calculator Returns Range Normalized Metric Time
JaroWinkler similarity and distance [0.0, 1.0] Yes No O(m*n)
LongestCommonSubsequence distance and length [0, m+n] No No O(m*n)
MetricLCS distance [0.0, 1.0] Yes Yes O(m*n)
RatcliffObershelp similarity and distance [0.0, 1.0] Yes No O(m*n*min(m,n)) worst

Most methods return float values. LongestCommonSubsequence.length() returns an int, and LongestCommonSubsequence.distance() returns an int for non-identical inputs and the float 0.0 otherwise.

Jaro-Winkler

Jaro-Winkler is a similarity measure designed for short strings such as person names and for detecting typos (Winkler, 1990). It gives credit for matching characters, penalizes transpositions, and boosts strings that share a common prefix.

Two characters match when they are equal and at most floor(max_len / 2) - 1 positions apart (the window is 0 when max_len is less than 2). Let m be the number of matches and t the transposition count reported by matches(). The Jaro similarity is:

J = (m / len(s0) + m / len(s1) + (m - t) / m) / 3

If J is greater than the threshold (default 0.7), the Winkler prefix boost is applied:

J_w = J + min(0.1, 1 / max_len) * prefix * (1 - J)

The distance is 1 - J_w. Identical strings, including two empty strings, score 1.0; strings with no matching characters score 0.0.

from strsimpy import JaroWinkler

jaro_winkler = JaroWinkler()

print(jaro_winkler.similarity("My string", "My tsring"))
print(jaro_winkler.similarity("My string", "My ntrisg"))
print(jaro_winkler.distance("My string", "My tsring"))
print(jaro_winkler.similarity("martha", "marhta"))
print(jaro_winkler.similarity("dixon", "dicksonx"))
print(jaro_winkler.similarity("", ""))
print(jaro_winkler.similarity("abc", "xyz"))
0.9740740740740741
0.8962962962962963
0.025925925925925908
0.9611111111111111
0.8133333333333332
1.0
0.0

The threshold is configurable through the constructor:

print(JaroWinkler().get_threshold())
print(JaroWinkler(0.5).get_threshold())
0.7
0.5

Match details

matches() is a static method that exposes the counts behind the score as a list in the order [matches, transpositions, prefix, max_len], where max_len is the length of the longer input:

print(JaroWinkler.matches("martha", "marhta"))
print(JaroWinkler.matches("", "abc"))
print(JaroWinkler.matches("abc", "abc"))
[6, 1, 3, 6]
[0, 0, 0, 3]
[3, 0, 3, 3]

The method can also be called on an instance, for example JaroWinkler().matches(...), and returns the same list.

Longest Common Subsequence

The longest common subsequence (LCS) is the longest sequence of characters that appears in both strings in order, but not necessarily consecutively. Unlike a common substring, the characters do not need to occupy adjacent positions.

The distance is derived from the LCS length:

LCS_length = length(s0, s1)
distance   = len(s0) + len(s1) - 2 * LCS_length

The distance ranges from 0 (identical strings) to len(s0) + len(s1) (no common characters). It equals the Levenshtein distance when only insertions and deletions are allowed, or when a substitution costs twice as much as an insertion or deletion.

from strsimpy import LongestCommonSubsequence

lcs = LongestCommonSubsequence()

print(lcs.distance("AGCAT", "GAC"))
print(lcs.length("AGCAT", "GAC"))
print(lcs.distance("AGCAT", "AGCT"))
print(lcs.length("AGCAT", "AGCT"))
print(LongestCommonSubsequence.length("AGCAT", "GAC"))
print(lcs.distance("abc", "abc"))
4
2
1
4
2
0.0

For AGCAT and GAC, the LCS is GA (length 2), so the distance is 5 + 3 - 2 * 2 = 4. The final value is the float 0.0 because the inputs are identical; every other distance is a Python int.

length() is a static method, so it can be called either through the class or through an instance. The implementation keeps two rolling rows: O(m*n) time and O(len(s1)) extra space.

Metric LCS

MetricLCS normalizes the LCS length by the longer input, producing a distance in [0.0, 1.0] (Bakkelund, “An LCS-based string metric”):

distance = 1 - LCS_length / max(len(s0), len(s1))

Because it is derived from a longest common subsequence, it is a true metric: it is symmetric, zero only for equal strings, and satisfies the triangle inequality. Only distance() is provided; there is no similarity() method.

from strsimpy import MetricLCS

metric_lcs = MetricLCS()

print(metric_lcs.distance("ABCDEFG", "ABCDEFHJKL"))
print(metric_lcs.distance("ABDEF", "ABDIF"))
print(metric_lcs.distance("", "abc"))
print(metric_lcs.distance("上海", "上海市"))
0.4
0.19999999999999996
1.0
0.33333333333333337

The second value is mathematically 0.2; the printed value is the nearest binary floating-point representation. It runs in O(m*n) time with O(len(s1)) extra space.

Ratcliff-Obershelp

RatcliffObershelp implements Gestalt pattern matching. It repeatedly finds the longest common substring of two strings, counts it, and recurses on the parts to its left and right. The similarity is:

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

Here matched is the total number of characters collected by all of the longest-common-substring passes. This is the algorithm behind Python’s difflib.SequenceMatcher.ratio(); compare with autojunk=False for inputs where Python’s automatic junk heuristic would otherwise apply.

from strsimpy import RatcliffObershelp

ratcliff = RatcliffObershelp()

print(ratcliff.similarity("abcd", "bcde"))
print(ratcliff.similarity("bcd", "aadcbbddd"))
print(ratcliff.similarity("aadcbbddd", "bcd"))
print(ratcliff.similarity("a b", "ab"))
print(ratcliff.distance("abcd", "bcde"))
0.75
0.3333333333333333
0.16666666666666666
0.8
0.25

Identical strings score 1.0; if either input is empty, the similarity is 0.0 (except that two empty strings score 1.0).

Tie-breaking and asymmetries

Ties between equally long common substrings are resolved the same way as Python’s difflib: earliest start in the first string, then earliest start in the second. This tie-breaking means the measure is not guaranteed to be symmetric when the inputs contain repeated patterns. The second and third values above are the two directions of the same pair: 1/3 and 1/6.

Whitespace is not normalized; spaces count as ordinary characters, which is why "a b" against "ab" scores 0.8 rather than 1.0.

Cost

The worst-case cost is O(m*n*min(m,n)). The implementation uses an explicit stack rather than recursion, so long repetitive inputs do not overflow the Python or Rust call stack. For long strings, difflib-style tie-breaking still applies.

Type to search…

↑↓ navigate↵ selectEsc close