Remove duplicate elements from a python chained list

Asked

Viewed 785 times

1

My code returns error when trying to run:

class No:
    def __init__(self,inidado):
        self.dado = inidado
        self.proximo = None

    def pegaDado(self):
        return self.dado

    def pegaProximo(self):
        return self.proximo

    def botaDado(self,novoDado):
        self.dado = novoDado

    def botaProximo(self,novoProximo):
        self.proximo = novoProximo

class ListaNaoOrdenada:
    def __init__ (self):
        self.inicio = None

    def Inserir(self,item):
        temp = No(item)
        temp.botaProximo(self.inicio)
        self.inicio = temp

    def Imprimir (self):
        atual = self.inicio
        while atual != None:
            print (atual.pegaDado())
            atual = atual.pegaProximo()

    def removeDuplicados(self):
        atual = segundo = self.inicio
        while atual != None:
            while segundo.pegaProximo != None:  
                if segundo.pegaProximo.pegaDado == atual.pegaDado:
                    segundo.pegaProximo = segundo.pegaProximo.pegaProximo  
                else:
                    segundo = segundo.pegaProximo

                atual = segundo = atual.pegaProximo
l = ListaNaoOrdenada()
l.Inserir(2)
l.Inserir(5)
l.Inserir(5)
l.Inserir(5)
l.Imprimir()
l.removeDuplicados()
l.Imprimir()

I wonder what to change to return only 2

  • And what is the error message?

1 answer

1


Hello,

I am not debugging the error in your code but python has a native data type which looks like an unordered list, and removes duplicates by definition: set (set in Portuguese).

Example:

>>> myset = set()
>>> myset.add(1)
>>> myset.add(5)
>>> myset.add(5)
>>> myset.add(5)
>>> print(myset)
{1, 5}

And of course, you can easily turn it into a list or a list orderly:

# Tranforma em lista.
>>> print(list(myset))
[1, 5]
>>> myset.add(-10)
>>> print(sorted(myset))
[-10, 1, 5]
  • Thanks for the help! The main difficulty was in debugging the code within the Listnaoordenada class, but with this set function helped a lot. Grateful!

  • @Mrpamonha, if you liked the solution you can "accept" it (to appear a green "ok" tick in the reply). Thank you : )

Browser other questions tagged

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