1

I want to be able to find whether all elements in list1 exist in list2, both lists containing chars. The number of times the same element appears in each list is important.

I tried using subsets however that didn't take note of the number of times an item appeared in a list

e.g.

list1 = [a, b, c]
list2 = [a, b, c, b]

It would find list2 a subset of list1, whereas I would only want my function to execute if:

list1 = [a, b, c, b, i]
list2 = [a, c, b, b]

as this means all items in list2 appear in list1.

If anyone was interested, using a counter was inefficient for large strings so I ended up adding all elements of list1 to a dictionary, with the values being number of occurances of each element and subtracted all elements of list2. If any values ended up negative not all items in list2 appear in list1

user2201609
  • 93
  • 4
  • 11

4 Answers4

4

You could count the items in both lists with collections.Counter and check that the counts for the corresponding items in the first list are >= than those in the second:

>>> from collections import Counter
>>> c = Counter("abcbi")
>>> d = Counter("acbb")
>>> c.subtract(d)
>>> if all(v >= 0 for k, v in c.items()):
...     print("All items exist")
... 
All items exist
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
1

You can use collections.Counter

from collections import Counter
list1 = ['a', 'b', 'c']
list2 = ['a', 'b', 'c', 'b']    
c1 = Counter(list1)
c2 = Counter(list2)

for key, count in c1.iteritems():
    if c2[key] < count:
        break
else:
    print 'list2 has all the chracters in list1'
Muhammad Tahir
  • 5,006
  • 1
  • 19
  • 36
0

You can use issuperset:

>>> list1 = ['a', 'b', 'c', 'b', 'i']
>>> list2 = ['a', 'c', 'b', 'b']
>>> set(list1).issuperset(set(list2)) # all items of list2 exist in list1
True
>>> set(list2).issuperset(set(list1)) # all items of list1 does not exist in list 2
False
Idos
  • 15,053
  • 14
  • 60
  • 75
0

For your problem, you'll need to

  1. Verify that all elements in list2 appear in list1 but
  2. No element in list2 appears more often than it does in list2

This can be done quite easily using collections.Counter:

import collections

def f(list1, list2):
    d1 = collections.Counter(list1)
    d2 = collections.Counter(list2)
    return set(d1.keys()).issuperset(set(d2.keys())) \
       and all(d2[k] <= d1[k] for k in d1.keys())

This first checks (using set.issuperset) that all the different elements of list2 are contained in list1. If that's true, it checks how often each element occurs in list2 and verifies that it appears less often (or equally often) in list1.

Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207