def viterbi_segment(text, P):
    """Find the best segmentation of the string of characters, given the
    UnigramTextModel P."""
n = len(text)
words = [''] + list(text)
best = [1.0] + [0.0] * n
for i in range(n + 1):
    for j in range(0, i):
        w = text[j:i]
if P[w] * best[i - len(w)] >= best[i]:
    best[i] = P[w] * best[i - len(w)]
words[i] = w
sequence = []
i = len(words) - 1
while i > 0:
    sequence[0:0] = [words[i]]
i = i - len(words[i])
return sequence, best[-1]
Python Implementation of Viterbi Algorithm