(long post but read it entirely, solution is at the end).
Remove the found value or register it in another dict.
Better though is to count the number of apparitions inside each array and test how many are common.
For the second case, you'd have
Keep these values in dictionaries:
a_app = {3:1, 2:1, 5:1, 4:1}
b_app = {2:2, 4:1}
And now, it is simple:
for i in b:
if a_app.has_key(i) and a_app[i] > 0:
a_app[i] -= 1
The b_app
dictionary would be used in other case.
Here is a test script I wrote (testing all testcases issued here):
def f(a, b):
a_app = {}
for i in a:
if not a_app.has_key(i):
a_app[i] = 0
a_app[i] += 1
print a_app
for i in b:
print i, '=>',
if a_app.has_key(i) and a_app[i] > 0:
a_app[i] -= 1
print i, ' is in a',
print '.'
f([1,1,2],[1,1])
f([3,2,5,4],[2,4,2])
f([3,2,2,4],[2,4,2])
f([3,2,5,4],[2,3,2])
And here is the output:
$ python 1.py
{1: 2, 2: 1}
1 => 1 is in a .
1 => 1 is in a .
{2: 1, 3: 1, 4: 1, 5: 1}
2 => 2 is in a .
4 => 4 is in a .
2 => .
{2: 2, 3: 1, 4: 1}
2 => 2 is in a .
4 => 4 is in a .
2 => 2 is in a .
{2: 1, 3: 1, 4: 1, 5: 1}
2 => 2 is in a .
3 => 3 is in a .
2 => .
Everything is perfect and no order is lost :)
Edit: Updated with @Avaris's suggestions, this script looks like:
import collections
def f(a, b):
a_app = collections.Counter(a)
for i in b:
print i, '=>',
if i in a_app and a_app[i] > 0:
a_app[i] -= 1
print i, ' is in a',
print '.'
print ''
f([1,1,2],[1,1])
f([3,2,5,4],[2,4,2])
f([3,2,2,4],[2,4,2])
f([3,2,5,4],[2,3,2])