Comparing a sequence of letters to a list of words in python
<p>I have a list of letters which is in a particular order (think of old school texting, so my sequence of buttons here is 4266532)</p>

<pre><code>letters = [['g', 'h', 'i'], ['a', 'b', 'c'], ['m', 'n', 'o'], ['m', 'n', 'o'], ['j', 'k', 'l'], ['d', 'e', 'f']]
</code></pre>

<p>and a list of words</p>

<pre><code>words = ['i', 'am', 'an', 'old', 'man']
</code></pre>

<p>I want to see how many matched sentences there are for this sequence of letters compared to this word list.</p>

<p>For example the sequence of letters could equal 'i am old' or 'i an old' </p>

<p>EDIT: To clarify what I mean by sequence</p>

<p>on old phones that still have buttons instead of touch screen. each button (or number) has letters that are attached to it. For example the number/button '2' has the letters <code>['a','b','c']</code> attached to it. The number/button '3' has the letters <code>['d,'e','f']</code> attached to it. So my <code>letters</code> list above displays what letters could appear on the screen when you push <code>4266532</code></p>

<p>Not sure what your full criteria is but since your lists are going to be small you can do something like:</p>

<pre><code>from collections import Counter
from itertools import combinations, chain
letters = [['g', 'h', 'i'], ['a', 'b', 'c'], ['m', 'n', 'o'],['m', 'n', 'o'], ['j', 'k', 'l'], ['d', 'e', 'f']]
allowed = set(chain.from_iterable(letters))
words = ['i', 'am', 'an', 'old', 'man']

for phrase in combinations(words, 3):
    phrase_c = Counter(chain.from_iterable(phrase))
    if any((v &gt; 1 and k not in "mno") or k not in allowed for k, v in phrase_c.items()):
        continue
    print(phrase)
</code></pre>

<p>Which would give you:</p>

<pre><code>('i', 'am', 'old')
('i', 'an', 'old')
('i', 'old', 'man')
</code></pre>

<p>If words is always a subset of the letter you can remove the <code>if k not in "mno"</code></p>

<p>if you have to be in order then it is simpler, just make sure each letter from the phrase appears in the subsets and in the correct order:</p>

<pre><code>from collections import Counter
from itertools import combinations, chain

letters = [['g', 'h', 'i'], ['a', 'b', 'c'], ['m', 'n', 'o'], ['m', 'n', 'o'], ['j', 'k', 'l'], ['d', 'e', 'f']]

words = ['i', 'am', 'an', 'old', 'man']

for phrase in combinations(words, 3):
    for ind, letter in enumerate(chain.from_iterable(phrase)):
         if ind &gt;= len(letters) or letter not in letters[ind]:
            break
    else:
        print(phrase)
</code></pre>

<p>Which would give you:</p>

<pre><code>('i', 'am', 'old')
('i', 'an', 'old')
</code></pre>

<p>If you sort words based on the letter order and filter words that don't contain any letters from the set you can reduce the complexity quite a bit. You can also consider  the fact that you can only create at most phrases that have 6 letters i.e <code>4266532</code> </p>

python