List in Python with non-repeated values without using set function?

2

How can I create a list from the sum of two previous ones without some value appearing repeated, without using the set function?

Example:

>>>a = [1, 2, 3]
>>>b = [3, 4, 5]
>>>c = a + b
>>>print c
[1, 2, 3, 3, 4, 5]

Note: I can not use the set function to create a set because I have not yet seen that term in ICC classes. I am in loop exercises ( while ), but in the way I wrote the program (wrong, almost certain) I did not use any loops.

If you can help me using ties, it would be interesting

How am I doing without the while:

a = int(raw_input())
x = range(0, a, 3)
y = range(0, a, 5)
lista = x + y
soma = sum(lista) 
print soma
    
asked by anonymous 19.03.2016 / 03:23

2 answers

2

One way to do this would be:

a = [1, 2, 3]
b = [3, 4, 5]

c = []

for elemento in a:
    c.append(elemento)

for elemento in b:
    if elemento not in c:
        c.append(elemento)

What we are doing is: for each element of the first list, we put it in the result list. Then, for each element of the second list, if it is not already in the result list, we put it.

    
19.03.2016 / 03:38
3

You can do it most directly:

  • Using loops, you can test if a given element of the second is in the first list (and by the end if it is not)
  • With another loop, you can repeat this process to insert each element of the second list into the first

The bad thing about the direct way is that the runtime gets pretty slow if your lists are large. More precisely, if their lists have N elements, the time to merge directly will be of the order of N 2

We can shorten this time to something of the order of N * LOG (N) if we take advantage of the fact that the elements of the list are amenable (this is the set behind the rags, more or less). If you sort the two lists, you can merge them in a single pass. Of course, in order to do this you will have to learn how to sort a vector efficiently, which is a subject for another class: P

    
19.03.2016 / 03:38