---
title: Word error rate
url: https://gurkanozkan.ai/learn/coding/mle-word-error-rate-23/
markdown: https://gurkanozkan.ai/learn/coding/mle-word-error-rate-23.md
kind: coding
difficulty: Easy
topics:
  - Speech
  - Dynamic programming
  - Edit distance
json: https://gurkanozkan.ai/api/learn/coding/mle-word-error-rate-23.json
robots: noindex
---

# Word error rate

Split both strings on whitespace. Return `(S + D + I)/N`, where S, D and I come from the minimum word-level edit distance (unit cost substitution, deletion, insertion) and N is the number of reference words. Raise `ValueError` if the reference has no words.

## Signature

```python
def word_error_rate(reference: str, hypothesis: str) -> float: ...
```

## Examples

Each call and the value it should give.

```python
>>> close(word_error_rate('the cat sat', 'the cat sat'), 0.0)
True

>>> close(word_error_rate('the cat sat', 'the bat sat'), 0.333333)
True
```

## Hints

1. Run a word-level edit-distance DP (unit cost) between reference and hypothesis.
2. WER = (S + D + I) / N where N is the number of reference words.
3. Raise ValueError when the reference has no words; keep an O(M) rolling row.

## Reference solution

```python
def word_error_rate(reference, hypothesis):
    r = reference.split(); h = hypothesis.split()
    if not r:
        raise ValueError("empty reference")
    prev = list(range(len(h) + 1))
    for i in range(1, len(r) + 1):
        cur = [i] + [0] * len(h)
        for j in range(1, len(h) + 1):
            cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (r[i - 1] != h[j - 1]))
        prev = cur
    return prev[-1] / len(r)
```

## What a strong solution covers

- O(N·M) DP with an O(M) rolling row.
- Correct initial row/column.
- Notes that WER can exceed 1.
- Discusses text normalisation (case, punctuation) and alignment back-tracing for error analysis.

## Common mistakes

- dividing by hypothesis length
- character-level instead of word-level distance.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
