Hellmut Lister
Hellmut Lister

Reputation: 1

Merging two lists containing one occurrences of each item

So I'm trying to merge two lists and have it return one list with only one occurrence of each item. I was given the referenced code on how to look at the contents of each list:

# contains - returns true if the specified item is in the ListBag, and
# false otherwise.
def contains(self, item):
    return item in self.items

# containsAll - does this ListBag contain all of the items in
# otherBag?  Returns false if otherBag is null or empty. 
def containsAll(self, otherBag):
    if otherBag is None or otherBag.numItems == 0:
        return False
    other = otherBag.toList()
    for i in range(len(otherBag.items)):
        if not self.contains(otherBag.items[i]):
            return False
    return True

So I'm trying this:

def unionWith(self, other):
    unionBag = ListBag()

    if other is None or other.numItems == 0 and self.numItems == 0 or self is None:
        return unionBag.items

    for i in self.items:
        if not unionBag.contains(self.items[i]):
            unionBag.add(i)
    for i in other.items:
        if not unionBag.contains(other.items[i]):
            unionBag.add(i)
    return unionBag.items

However I get a "TypeError: argument of type 'NoneType' is not iterable" error. And I'm not sure how to get around that. So for expected input and output:

# A list has been already created with the following contents:
bag1.items
[2, 2, 3, 5, 7, 7, 7, 8]
bag2.items
[2, 3, 4, 5, 5, 6, 7]
# So the input/output would be
bag1.unionWith(bag2)
[2, 3, 4, 5, 6, 7, 8]

Upvotes: 0

Views: 82

Answers (1)

Israel Unterman
Israel Unterman

Reputation: 13510

This is very simple using Python's built in set. A set object keeps only unique values. Here is my call on this:

a = [2, 2, 3, 5, 7, 7, 7, 8]
b = [2, 3, 4, 5, 5, 6, 7]
c = list(set(a) | set(b))
print(c)

>>>
[2, 3, 4, 5, 6, 7, 8]

I converted the final set back to a list.

Upvotes: 2

Related Questions