Updated for challenge 9
[cipher-tools.git] / support / segment.py
1 import sys
2 from functools import lru_cache
3 from support.language_models import Pwords
4
5 sys.setrecursionlimit(1000000)
6
7 @lru_cache()
8 def segment(text):
9 """Return a list of words that is the best segmentation of text.
10 """
11 if not text: return []
12 candidates = ([first]+segment(rest) for first,rest in splits(text))
13 return max(candidates, key=Pwords)
14
15 def splits(text, L=20):
16 """Return a list of all possible (first, rest) pairs, len(first)<=L.
17 """
18 return [(text[:i+1], text[i+1:])
19 for i in range(min(len(text), L))]
20