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>Try that:</p>

<pre><code>def is_anagram(a, b):
    word = [filter(lambda x: x in a, sub) for sub in b]
    return ''.join(word)[0:len(a)]
</code></pre>

<p>Example:</p>

<pre><code>&gt;&gt;&gt; is_anagram('some','somexcv')
'some'
</code></pre>

<p><strong>Note:</strong> This code returns the <code>common word</code> if there is any or <code>''</code> otherwise. (it doesn't return <code>True/False</code> as the OP asked - realized that after, but anyway this code can easily change to adapt the <code>True/False</code> type of result - I won't fix it now such there are great answers in this post that already do :) )</p>

<blockquote>
  <p>Brief explanation:</p>
</blockquote>

<p>This code takes(<code>filter</code>) every letter(<code>sub</code>) on <code>b</code> word that exists in <code>a</code> word also. Finally returns the word which must have the same length as a(<code>[0:len(a)]</code>). The last part with <code>len</code> needs for cases like this:
<code>is_anagram('some','somenothing')</code> </p>

python python-2.7 python-3.x