---
title: "Shingle-based algorithms"
description: "Compare strings with k-shingle profiles and sets using NGram, QGram, Cosine, Jaccard, Sorensen-Dice, Overlap, Tversky, and Tanimoto."
---

> Documentation Index
> Fetch the complete documentation index at: https://luozhouyang.github.io/python-string-similarity/llms.txt
> Use this file to discover all available pages before exploring further.

# Shingle-based algorithms

Most measures on this page turn a string into its **k-shingles**: every contiguous window of `k` characters. For `k = 2`, `"night"` becomes `ni`, `ig`, `gh`, and `ht`. The measures differ in whether they keep the number of occurrences of each shingle and in how they combine the resulting collections.

For the profile-based measures, the cost is dominated by k-shingling. For large datasets, compute each string's profile once, then compare the cached representations instead of re-shingling on every pair.

## Profiles versus sets

Two representations are used:

- A **profile** maps each distinct shingle to the number of times it occurs. `QGram` and `Cosine` use profiles, so repeated shingles contribute.
- A **set** contains each distinct shingle once, ignoring counts. `Jaccard`, `SorensenDice`, `OverlapCoefficient`, `Tversky`, and `Tanimoto` use sets.

With `k = 2`, `"aaaa"` has the profile `{'aa': 3}` but the set `{'aa'}`. The profile sees the extra occurrences, so `QGram(2).distance("aaaa", "aa")` is `2`; the set measures ignore them, so `Jaccard(2).similarity("aaaa", "aa")` is `1.0`.

```python
from strsimpy.qgram import QGram

qgram = QGram(2)
print(sorted(qgram.get_profile("ABCD").items()))
print(sorted(qgram.get_profile("a  b").items()))
print(qgram.get_profile("aaaa"))
```

```text
[('AB', 1), ('BC', 1), ('CD', 1)]
[(' b', 1), ('a ', 1)]
{'aa': 3}
```

### Whitespace normalization

Before shingling, every class on this page that builds a profile applies Python's `re.sub(r"\s+", " ", text)`: each run of Python whitespace becomes a single ASCII space. Leading and trailing whitespace is collapsed to one space but is not removed.

The normalization happens before windows are taken, which is why `qgram.get_profile("a  b")` above contains the shingles `"a "` and `" b"`. As a consequence, `"Shang  Hai"` and `"Shang Hai"` produce the same profile for a given `k`.

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

Because a profile does not record its shingle size, only compare profiles built with the same `k`. Keep one configured instance or one explicit `k` for all strings in a dataset.

## N-Gram (Kondrak)

`NGram` implements Kondrak's normalized n-gram distance. It does not use the shingle profile machinery of the other classes: it compares the raw character sequences, conceptually prefixes the first string with `n - 1` padding markers that cannot match an input character to give more weight to the start, and normalizes the resulting edit cost by the length of the longest original string.

The result is in the range `[0.0, 1.0]`; identical strings have distance `0.0`. `NGram` exposes only `distance()`: it has no `similarity()`, no `get_k()`, and no `get_profile()`. The constructor is `NGram(n=2)`, and `n` must be greater than zero (`NGram(0)` raises `ValueError`). The `n` attribute can be read and reassigned.

```python
from strsimpy.ngram import NGram

print(NGram(2).distance("ABCD", "ABTUIO"))
print(NGram(2).distance("ShangHai", "Shang Hai"))
print(NGram(2).distance("上海", "上海市"))
```

```text
0.5833333333333334
0.16666666666666666
0.3333333333333333
```

Because `"ShangHai"` and `"Shang Hai"` differ by the space, their distance is `1/6`, not `0`: input whitespace is an ordinary character. Q-Gram and the set measures collapse runs of whitespace to one space, but they still treat that single space as a character; they are not insensitive to the presence of a space. Padding is also distinct from every input character in this implementation, so a newline in the input is never mistaken for padding.

## Q-Gram

Q-Gram distance (Ukkonen) is the L1 norm of the difference between the two profiles:

```text
D(s0, s1) = SUM over shingles |count0(shingle) - count1(shingle)|
```

It counts occurrences, so unequal pairs produce an integer L1 distance. Equal raw strings take a shortcut in the Python binding and return `0.0` (a float). Q-Gram is a cheap profile-based alternative to character-level alignment: once profiles are built, comparing them is linear in the number of distinct shingles, rather than the quadratic cost of a full edit-distance calculation.

The class provides only a distance; there is no `similarity()` method. If a normalized similarity is needed, use one of the similarity measures on this page.

```python
from strsimpy.qgram import QGram

qgram = QGram(2)
print(qgram.get_profile("aaaa"))
print(qgram.distance("ABCD", "ABCE"))
print(qgram.distance("aaaa", "aa"))

profile0 = qgram.get_profile("ABCD")
profile1 = qgram.get_profile("ABCE")
print(QGram.distance_profile(profile0, profile1))
```

```text
{'aa': 3}
2
2
2
```

`QGram.distance_profile()` is a static method and also works when called on an instance. In 0.5.0, it and `Cosine.similarity_profiles()` accept plain dictionaries as well as read-only mapping wrappers such as `types.MappingProxyType` and `collections.UserDict`.

The constructor defaults to `k = 3`: `QGram(k=3)`.

## Cosine similarity

Cosine similarity treats each profile as a vector of counts:

```text
sim(s0, s1) = (V0 . V1) / (||V0|| * ||V1||)
```

Counts matter, but only through their relative proportions, so `Cosine(2).similarity("aaaa", "aa")` is `1.0`. The distance is `1 - similarity`.

```python
from strsimpy.cosine import Cosine

cosine = Cosine(2)
s0 = "My first string"
s1 = "My other string..."

print(cosine.similarity(s0, s1))
print(cosine.distance(s0, s1))
print(cosine.similarity_profiles(cosine.get_profile(s0), cosine.get_profile(s1)))
```

```text
0.5161854012087639
0.4838145987912361
0.5161854012087639
```

If either profile has zero norm (for example, whitespace normalization leaves no shingle of length `k`), `similarity_profiles()` returns `0.0` and `distance()` returns `1.0`. The direct string method first special-cases raw equality, so two identical whitespace-only strings are still similar with `1.0`.

```python
from strsimpy.cosine import Cosine

cosine = Cosine(4)
print(cosine.similarity("    ", "foo bar"))
print(cosine.distance("    ", "foo bar"))
print(cosine.similarity("    ", "    "))
print(cosine.similarity_profiles({}, {}))
```

```text
0.0
1.0
1.0
0.0
```

`Cosine` requires an explicit shingle size: `Cosine(k)`. There is no default.

## Jaccard index

The Jaccard index ignores counts and treats each string as a set of shingles:

```text
sim(s0, s1) = |A intersect B| / |A union B|
```

The distance is `1 - similarity`. The Jaccard distance is a metric, which makes it suitable for indexes and nearest-neighbor searches that rely on the triangle inequality.

```python
from strsimpy.jaccard import Jaccard

jaccard = Jaccard(2)
print(jaccard.similarity("car", "bar"))
print(jaccard.distance("car", "bar"))
print(jaccard.similarity("aaaa", "aa"))
```

```text
0.3333333333333333
0.6666666666666667
1.0
```

`Jaccard` requires an explicit shingle size: `Jaccard(k)`. Identical raw strings are special-cased to `1.0` before profiles are built. Two different strings that both produce empty profiles have similarity `0.0` and distance `1.0`, so whitespace-only inputs behave as follows:

```python
from strsimpy.jaccard import Jaccard

print(Jaccard(3).similarity("   ", "   "))
print(Jaccard(3).similarity("   ", "    "))
```

```text
1.0
0.0
```

The first pair is equal as raw strings. The second pair is not equal, and neither input yields a 3-shingle after normalization, so there is no set to compare.

## Sorensen-Dice coefficient

The Sorensen-Dice coefficient uses set semantics as well:

```text
sim(s0, s1) = 2 * |A intersect B| / (|A| + |B|)
```

The distance is `1 - similarity`. Unlike Jaccard, this distance is not a metric. Identical raw strings have similarity `1.0`; if the profiles of two different strings are both empty, the similarity is `0.0` rather than a division by zero.

```python
from strsimpy.sorensen_dice import SorensenDice

dice = SorensenDice(2)
print(dice.similarity("上海", "上海市"))
print(dice.distance("上海", "上海市"))
```

```text
0.6666666666666666
0.33333333333333337
```

The constructor defaults to `k = 3`: `SorensenDice(k=3)`.

## Overlap coefficient

The overlap coefficient (Szymkiewicz-Simpson) normalizes the intersection by the smaller set:

```text
sim(s0, s1) = |A intersect B| / min(|A|, |B|)
```

Because the denominator is the smaller set, similarity is always `1.0` when one shingle set is a subset of the other. This tends to produce higher scores than Jaccard or Sorensen-Dice. The distance is `1 - similarity` and is not a metric.

```python
from strsimpy.overlap_coefficient import OverlapCoefficient

print(OverlapCoefficient(3).similarity("eat", "eating"))
print(OverlapCoefficient(3).distance("eat", "eating"))
print(OverlapCoefficient(2).similarity("car", "bar"))
print(OverlapCoefficient(2).distance("car", "bar"))
```

```text
1.0
0.0
0.5
0.5
```

The constructor defaults to `k = 3`: `OverlapCoefficient(k=3)`.

## Tversky index

The Tversky index generalizes Jaccard and Sorensen-Dice by weighting the two set differences independently:

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

The inputs are converted to **sets** of k-shingles, so repeated shingles are counted once. With `alpha = beta = 1.0` the index is the Jaccard index; with `alpha = beta = 0.5` it is the Sorensen-Dice coefficient.

```python
from strsimpy.tversky 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"))
print(Tversky(2, 1.0, 1.0).similarity("aaa", "aa"))
```

```text
0.5
0.6666666666666666
1.0
1.0
```

When `alpha != beta`, the index is asymmetric. `alpha` weights shingles present only in the first argument, and `beta` weights shingles present only in the second. The middle two values are the same pair in opposite directions with `alpha = 1.0` and `beta = 0.0`: extra shingles in the first string lower the score, while extra shingles in the second string do not. The distance is `1 - similarity`, so it is asymmetric as well and not a metric in that case.

The final value illustrates set semantics. For `k = 2`, `"aaa"` and `"aa"` both produce the set `{'aa'}`, so the similarity is `1.0`. TextDistance counts duplicate shingles as a multiset and would produce `2/3` for this pair.

The constructor is `Tversky(k=3, alpha=1.0, beta=1.0)`. Both `alpha` and `beta` must be finite, non-negative, and not both zero; otherwise the constructor raises `ValueError`. `alpha` and `beta` are available as attributes, and `get_k()` returns the shingle size.

## Tanimoto similarity

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

```text
sim(s0, s1) = |A intersect B| / |A union B|
```

`Tanimoto(k)` therefore delegates to `Jaccard(k)` and shares its set semantics and empty-profile behavior. The distance is `1 - similarity` and is a metric.

```python
from strsimpy.tanimoto import Tanimoto

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

```text
0.14285714285714285
0.8571428571428572
```

This is deliberately not TextDistance's Tanimoto, which returns `log2(Jaccard)`, produces negative similarities for partial overlap, and returns negative infinity for disjoint inputs. This library implements the standard set-based coefficient. Only the set or binary definition is exposed; the extended real-valued count-vector variant is not implemented.

The constructor defaults to `k = 3`: `Tanimoto(k=3)`.

## Shingle sizes and profile helpers

| Class | Constructor default | Shingle size and profiles | Notes |
| --- | --- | --- | --- |
| `NGram` | `NGram(n=2)` | `.n` property; no profile helpers | Raw characters; `distance()` only; does not normalize whitespace |
| `QGram` | `QGram(k=3)` | `get_k()`, `get_profile()`, `QGram.distance_profile()` | Profiles; L1 distance; equal inputs return `0.0` |
| `Cosine` | `Cosine(k)` required | `get_k()`, `get_profile()`, `similarity_profiles()` | Profiles; distance is `1 - similarity` |
| `Jaccard` | `Jaccard(k)` required | `get_k()`, `get_profile()` | Sets; metric distance |
| `SorensenDice` | `SorensenDice(k=3)` | `get_k()`, `get_profile()` | Sets |
| `OverlapCoefficient` | `OverlapCoefficient(k=3)` | `get_k()`, `get_profile()` | Sets; subset implies similarity `1.0` |
| `Tversky` | `Tversky(k=3, alpha=1.0, beta=1.0)` | `get_k()`, `get_profile()` | Sets; asymmetric when `alpha != beta` |
| `Tanimoto` | `Tanimoto(k=3)` | `get_k()`, `get_profile()` | Sets; identical to `Jaccard` |

All profile-based classes also expose a `k` attribute for the shingle size, while `NGram` uses `n`. `get_profile()` returns a plain dictionary, so profiles can be cached and compared later with `QGram.distance_profile()` or `Cosine.similarity_profiles()`.

## Related

- [Algorithms overview](https://luozhouyang.github.io/python-string-similarity/algorithms/)
- [Edit distance algorithms](https://luozhouyang.github.io/python-string-similarity/algorithms/edit-distance/) for Levenshtein and the other character-level measures that Q-Gram complements
- [Compatibility with other libraries](https://luozhouyang.github.io/python-string-similarity/guides/compatibility/) for the differences from TextDistance, including Tversky set semantics and Tanimoto

Source: https://luozhouyang.github.io/python-string-similarity/algorithms/shingle-based/index.mdx
