coin1002
coin1002

Reputation: 55

Combine two lists using classes (Python)

So I want to create two list objects and combine them using function union in class MySet. So far I have

class MySet:
    def __init__(self, elements):
        self.elements=elements
    def union(self, sets):
        for i in self.elements:
            self.elements.append(sets)
            break
        for j in self.elements and sets
            #print j only once
            #idk if even the first part is the right syntax

So to use it I would do

seta = MySet([1,2,3])
setb = MySet([1,10,11])
setc = seta.union(setb)

Also, I don't want it to print duplicates. So setc.elements should output [1,2,3,10,11]. And seta.elements should still be [1,2,3] and so on. Thank you.

Upvotes: 1

Views: 1922

Answers (4)

klim
klim

Reputation: 1269

The answer of @aneroid is good, but would be very slow if other_set is large. Using set is one of the most scalable choices. The order will be ignored.

def union(self, other_set):
    return list(set(self.elements).union(other_set))

If you want to keep the order, making a set object would be faster for very large other_set.

def union(self, other_set):
    new_set = [i for i in self.elements]  # which is actually a list
    set_obj = set(new_set)
    for j in other_set:
        if j not in set_obj:
            new_set.append(j)
    return new_set

Upvotes: 0

vash_the_stampede
vash_the_stampede

Reputation: 4606

This setup would accomplish what you are speaking of, just set up the method to concatenate the two list, how you call the methods is important.

class MySet:
    def __init__(self, elements):
        self.elements=elements
    def union(self,set_2):
        return list(set(self.elements) | set(set_2))

seta = MySet([1, 2, 3])
setb = MySet([1, 10, 11])
setc = seta.union(setb.elements)

print(seta.elements) # => [1, 2, 3]
print(setb.elements) # => [1, 10, 11]
print(setc) # => [1, 2, 3, 10, 11]

Upvotes: 0

aneroid
aneroid

Reputation: 15962

If you want set-like behaviour, use actual sets.

new_set = set(seta) + set(setb)  # seta & setb are lists

But if you really need to use a class which behaves like a list, change the union() function to this:

def union(self, other_set):
    new_set = [i for i in self.elements]  # which is actually a list
    for j in other_set:
        if j not in self.elements:
            new_set.append(j)
    return new_set

First, new_set is being created as copy of self (seta). Then, each element of other_set (setb) which is not in self gets added, in order, to the new set.

Upvotes: 0

Kingsley
Kingsley

Reputation: 14906

Python Sets are a good way of doing this.

def union(self, new_set):
    seta = set(self.elements)
    setb = set(new_set)
    set_diff = setb - seta  # remove any overlap
    return self.elements + list(set_diff)

Upvotes: 1

Related Questions