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>If you need to check if <code>a</code> word could be created from <code>b</code> you can do this</p>

<pre><code>def is_anagram(a,b):
    b_list = list(b)
    for i_a in a:
        if i_a in b_list:
            b_list.remove(i_a)
        else:
            return False
    return True
</code></pre>

<p><strong>UPDATE(Explanation)</strong></p>

<p><code>b_list = list(b)</code> makes a <code>list</code> of <code>str</code> objects(characters). </p>

<pre><code>&gt;&gt;&gt; b = 'asdfqwer'
&gt;&gt;&gt; b_list = list(b)
&gt;&gt;&gt; b_list
['a', 's', 'd', 'f', 'q', 'w', 'e', 'r']
</code></pre>

<p>What basically is happening in the answer: We check if every character in <code>a</code> listed in <code>b_list</code>, when occurrence happens we remove that character from <code>b_list</code>(we do that to eliminate possibility of returning <code>True</code> with input <code>'good'</code>, <code>'god'</code>). So if there is no occurrence of another character of <code>a</code> in rest of <code>b_list</code> then it's not advanced anagram.</p>

python python-2.7 python-3.x