Python - Checking if all and only the letters in a list match those in a string?
<p>I'm creating an <strong>Anagram Solver</strong> in <strong>Python 2.7</strong>.</p>

<p>The solver takes a user inputted anagram, converts each letter to a list item and then checks the list items against lines of a '.txt' file, appending any words that match the anagram's letters to a <code>possible_words</code> list, ready for printing.</p>

<p>It works... <em>almost!</em></p>

<hr>

<pre><code># Anagram_Solver.py

anagram = list(raw_input("Enter an Anagram: ").lower())

possible_words = []

with file('wordsEn.txt', 'r') as f:

    for line in f:

        if all(x in line + '\n' for x in anagram) and len(line) == len(anagram) + 1:

            line = line.strip()
            possible_words.append(line)

print "\n".join(possible_words)
</code></pre>

<hr>

<p>For anagrams with no duplicate letters it works fine, but for words such as 'hello', the output contains words such as 'helio, whole, holes', etc, as the solver doesn't seem to count the letter 'L' as being 2 separate entries?</p>

<p>What am I doing wrong? I feel like there is a simple solution that I'm missing?</p>

<p>Thanks!</p>

<p>Your code does as it's expected. You haven't actually made it check whether a letter appears twice (or 3+ times), it just checks <code>if 'l' in word</code> twice, which will always be True for all words with at least one <code>l</code>.</p>

<p>One method would be to count the letters of each word. If the letter counts are equal, then it is an anagram. This can be achieved easily with the <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow">collections.Counter</a> class:</p>

<pre><code>from collections import Counter
anagram = raw_input("Enter an Anagram: ").lower()

with file('wordsEn.txt', 'r') as f:
    for line in f:
        line = line.strip()
        if Counter(anagram) == Counter(line):
            possible_words.append(line)

print "\n".join(possible_words)
</code></pre>

<p>Another method would be to use <a href="https://docs.python.org/2/library/functions.html#sorted" rel="nofollow">sorted()</a> function, as suggested by Chris in the other answer's comments. This sorts the letters in both the anagram and line into alphabetical order, and then checks to see if they match. This process runs faster than the collections method.</p>

<pre><code>anagram = raw_input("Enter an Anagram: ").lower()

with file('wordsEn.txt', 'r') as f:
    for line in f:
        line = line.strip()
        if sorted(anagram) == sorted(line):
            possible_words.append(line)

print "\n".join(possible_words)
</code></pre>

python list python-2.7 pattern-matching anagram