union of lists

Asked

Viewed 426 times

2

I am doing this algorithm where I have to do the union of two lists and the repeated numbers can only appear once. But it’s gone wrong, someone to save me?

def uniao(l1,l2,r=[]):
    if len(l1) == 0:
            return r
        else:
            if l1[0] in r and l1[0] not in l2:
                return uniao(l1[1:],l2,r)
            else:
                return uniao(l1[1:],l2,r + [l1[0]]+[l2[0]])
  • 3

    How did you see it going wrong? What test did you do? What was the result obtained and what was expected? In fact, be careful when defining a mutable object as the default value of a parameter, such as the list (read more in When a default argument is evaluated in Python?). In fact, review the indentation of your code in the question; we have no way of knowing if this is wrong in the code or if it was just a formatting error here in the question.

  • 1

    It was to appear as a result [1,2,3,5], but it appears [1, 1, 2, 1, 3, 1]

  • 1

    Well, it depends on the entry lists for that... Try to do the table test of your code.

2 answers

1

From what I understand, you’re making a function that checks the data of two array’s and adds in the first one what you have in the second but not in the first one.

If that’s correct, follow the code:

def uniao (l1,l2):
    r = []
    for a in l1:
        r.append(a)
    for i in l2:
        if i in r:
            pass
        else:
            r.append(i)
    return r

l1 = [1,2,3,4]
l2 = [4,5,6,7]

print(uniao(l1,l2))

1

You can try

def uniao(l1,l2):
    return list(set(l1+l2))

In this case, you join the two lists, make a set() on them (which will make it have only unique values, but in the {} format) and then move into a list. You have the unique values of the two lists.

As you can see at this link, set() takes unique values and leaves them sorted (if you have a shuffled list of values).

EDITED:

You can also make a function that can receive a greater variety of lists, passing the function with *args argument and iterating through it as in the example below:

def uniao(*arg):
    return list(set([j for i in arg for j in i]))

For example:

l1 = [1,2,3]
l2 = [1,2,5]
l3 = [1,2,3,4]
print(uniao(l1,l2,l3))

>> [1, 2, 3, 4, 5]

So, you can pass the number of lists you want, remembering that this will not work if you pass a number.

In order to use something other than a list, you can also do the code as follows:

def uniao(*arg):
    lista = []
    for i in arg:
        if type(i) == list:
            for j in i:
                lista.append(j)
        else:
            lista.append(i)
    return list(set(lista))

l1 = [1,2,3]
l2 = [1,2,5]
l3 = [1,2,3,4]
l4 = 6

print(uniao2(l1,l2,l3,l4))

>>  [1, 2, 3, 4, 5, 6]
  • It would be possible to do this joint function without the integrated functions???

  • Could be more specific?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.