Basic Anagram VS more advanced one
<p>I'm currently working my way through a "List" unit and in one of the exercises we need to create an anagram (for those who don't know; <em>two words are an anagram if you can rearrange the letters from one to spell the other</em>).</p>

<p>The easier solution that comes to mind is:</p>

<pre><code>def is_anagram(a, b):
    return sorted(a) == sorted(b)

print is_anagram('god', 'dog')
</code></pre>

<p>It works, but it doesn't really satisfy me. If we were in this situation for example:</p>

<pre><code>def is_anagram(a, b):
    return sorted(a) == sorted(b)

print is_anagram('god', 'dyog') #extra letter 'd' in second argument
&gt;&gt;&gt; False
</code></pre>

<p>Return is False, although we should be able to to build the word <code>'god'</code> out of <code>'dyog'</code>. Perhaps this game/problem isn't called an anagram, but I've been trying to figure it out anyway.</p>

<p><strong>Technically my solution is to:</strong><br>
1- Iterate through every element of b.<br>
2- As I do, I check if that element exists in a.<br>
3- If all of them do; then we can create a out of b.<br>
4- Otherwise, we can't.</p>

<p>I just can't seem to get it to work. <strong>For the record, I do not know how to use <code>lambda</code></strong></p>

<p><strong>Some tests:</strong></p>

<pre><code>print is_anagram('god', 'ddog') #should return True
print is_anagram('god', '9d8s0og') #should return True
print is_anagram('god', '_@10d_o g') #should return True
</code></pre>

<p>Thanks :)</p>

<p>Since the other answers do not, at time of writing, support reversing the order:</p>

<p>Contains <a href="https://www.python.org/dev/peps/pep-0484/" rel="nofollow">type hints</a> for convenience, because why not?</p>

<pre><code># Just strip hints out if you're in Python &lt; 3.5.
def is_anagram(a: str, b: str) -&gt; bool:
    long, short = (a, b) if len(a) &gt; len(b) else (b, a)
    cut = [x for x in long if x in short]
    return sorted(cut) == sorted(short)
</code></pre>

<p>If, in future, you do learn to use <code>lambda</code>, an equivalent is:</p>

<pre><code># Again, strip hints out if you're in Python &lt; 3.5.
def is_anagram(a: str, b: str) -&gt; bool:
    long, short = (a, b) if len(a) &gt; len(b) else (b, a)
    # Parentheses around lambda are not necessary, but may help readability
    cut = filter((lambda x: x in short), long)
    return sorted(cut) == sorted(short)
</code></pre>

python python-2.7 python-3.x