---
title: "Token-based algorithms"
description: "Compare character multisets and whitespace-separated tokens with Bag distance and Monge-Elkan similarity."
---

> 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.

# Token-based algorithms

The two measures in this family work at different units from the shingle-based algorithms. `Bag` treats a string as a multiset of characters; `MongeElkan` treats it as a sequence of whitespace-separated tokens. Neither builds a shingle profile, and neither applies the whitespace normalization used by the shingle classes.

## Bag distance

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

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

Here `A` and `B` are character multisets, so character order and position are ignored and repeated characters count. The result is a non-negative integer. Anagrams have distance `0`. Bag distance is symmetric, satisfies the triangle inequality, and is a metric. It is also a cheap lower bound and filter for edit distance: if the bags differ by more than a candidate threshold, no edit-distance algorithm can score the pair below that threshold.

`Bag` provides only `distance()`. There is no `similarity()` and no normalized form; divide by `max(len(s0), len(s1))` when the longer string is non-empty if a value in `[0.0, 1.0]` is needed. The constructor takes no arguments: `Bag()`.

Bag does not normalize whitespace: spaces are ordinary characters, so `Bag().distance("q w", "qw")` is `1`.

```python
from strsimpy.bag import Bag

bag = Bag()
print(bag.distance("qwe", "ewq"))
print(bag.distance("qwe", "rtys"))
print(bag.distance("", "abc"))
print(bag.distance("q w", "qw"))
```

```text
0
4
3
1
```

`Bag().distance("aab", "abb")` is also `1`, because the two bags share one `a` and one `b` and each has one character left over.

## Monge-Elkan

Monge-Elkan compares two token sequences with a secondary string similarity:

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

Each token of the first sequence is matched with its best match in the second sequence, and those best scores are averaged over the first sequence. `distance()` is `1 - similarity()`, so it also lies in `[0.0, 1.0]`.

### Tokenization

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

### Inner similarity

The secondary similarity is selected with the `inner` argument:

- `"jaro_winkler"` (the default)
- `"normalized_levenshtein"`

Any other value raises `ValueError`. The selected value is available as the `inner` attribute, and `symmetric` reports whether the symmetric variant is enabled.

```python
from strsimpy.monge_elkan import MongeElkan

monge_elkan = MongeElkan()
print(monge_elkan.similarity("Niall", "Neal"))
print(round(monge_elkan.similarity("Niall", "Neal"), 3))
print(monge_elkan.similarity("a b", "b c"))
print(monge_elkan.similarity("new york", "york new"))
```

```text
0.8049999999999999
0.805
0.5
1.0
```

The single-token score `0.8049999999999999` rounds to `0.805`. For `"new york"` and `"york new"`, every token finds an identical token in the other sequence, so the score is `1.0` despite the different order.

### Asymmetry and the symmetric option

By default the score is asymmetric, because the average runs over the tokens of the first argument only:

```python
from strsimpy.monge_elkan import MongeElkan

monge_elkan = MongeElkan()
print(monge_elkan.similarity("a b", "a"))
print(monge_elkan.similarity("a", "a b"))
print(MongeElkan(symmetric=True).similarity("a b", "a"))
```

```text
0.5
1.0
0.75
```

The first call averages the best matches for `a` and `b` against `a`, giving `(1.0 + 0.0) / 2 = 0.5`. The second call averages only `a`, which matches perfectly, giving `1.0`. With `symmetric=True`, the two directions are averaged: `(0.5 + 1.0) / 2 = 0.75`.

Use `symmetric=True` when the score must not depend on argument order. The default asymmetry follows the original Monge-Elkan definition.

### Using normalized Levenshtein

```python
from strsimpy.monge_elkan import MongeElkan

levenshtein_me = MongeElkan(inner="normalized_levenshtein")
print(levenshtein_me.similarity("Niall", "Neal"))
print(levenshtein_me.similarity("abc", "abd"))
```

```text
0.6
0.6666666666666667
```

### Empty token lists

Both token lists being empty yields similarity `1.0`. Exactly one empty token list yields `0.0`. Because tokenization is whitespace-based, empty and whitespace-only strings have no tokens.

```python
from strsimpy.monge_elkan import MongeElkan

monge_elkan = MongeElkan()
print(monge_elkan.similarity("", ""))
print(monge_elkan.similarity("   ", "\t\n"))
print(monge_elkan.similarity("a", ""))
print(monge_elkan.similarity("", "a"))
```

```text
1.0
1.0
0.0
0.0
```

These conventions apply in both asymmetric and symmetric mode.

### TextDistance compatibility

TextDistance's multi-token Monge-Elkan implementation divides the aggregate by `|A|^2` rather than `|A|`, so its scores are too low whenever the first argument has more than one token. For example, it reports `0.25` instead of `0.5` for `("a b", "b c")`. This library uses the standard formula above; the two implementations agree only for single-token inputs. See [Compatibility with other libraries](https://luozhouyang.github.io/python-string-similarity/guides/compatibility/) for the full list of divergences.

## At a glance

| Measure | Unit | Methods | Symmetric | Whitespace handling |
| --- | --- | --- | --- | --- |
| `Bag` | Characters (multiset) | `distance()` | Yes | Counted as ordinary characters |
| `MongeElkan` | Whitespace-separated tokens | `similarity()`, `distance()` | Only with `symmetric=True` | Used as a separator; runs are ignored |

## 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 which Bag distance is a lower bound and normalized Levenshtein is an inner Monge-Elkan measure
- [Compatibility with other libraries](https://luozhouyang.github.io/python-string-similarity/guides/compatibility/) for differences from TextDistance, including the Monge-Elkan denominator

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