Exercise list ordering

Asked

Viewed 68 times

1

Good afternoon,

I am developing an exercise and in a moment I have to order a list and remove elements repeated, for this I perform the conversion to set and then convert to list again:

    def remove(lista):
       lista2 = set(lista)
       lista = list(lista2)
       return lista

however performing a test, I always get an unexpected result, in the conversion of [7,3,33,12,3,3,3,3,7,12,100] instead of getting [3,7,12,33,100], I get as a result [33, 3, 12, 100, 7], someone can help me find this error?

2 answers

0

To remove the repeated values and sort the list you citou in the example, you can use the following algorithm...

numeros = [7, 3, 33, 12, 3, 3, 3, 7, 12, 100]

resultado = list()
for c in numeros:
    if c not in resultado:
        resultado.append(c)
resultado.sort()
print(resultado)

See here the functioning of the algorithm.

Now, if you plan to work with lists of tamanhos and elementos varied, you can use the following algorithm...

numeros = list(map(int, input('Digite os elementos da lista: ').split()))

resultado = list()
for c in numeros:
    if c not in resultado:
        resultado.append(c)
resultado.sort()
print(resultado)

See here the functioning of the algorithm.

Note that when you run this último algorithm, you will have to type todos the elements of the list in mesma linha, separated by a espaço.

0


No mistake, you simply did not order the list after removing duplicates:

def remove(lista):
   return sorted(set(lista)) # <--- ordena lista

DOCS

Browser other questions tagged

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