Program to remove ONLY a copy of duplicate values from a list

Asked

Viewed 94 times

-2

Write a method rem() that accepts as input a list possibly containing duplicate values, and return a copy of the list where a copy of each duplicate value is removed. What I did:

    def rem(lista):
    i = 0
    while i <= len(lista):
        # print(lista[i])
        if lista.count(i) >= 2:
            lista.remove(i)
        i += 1
    print(lista)

lista = [3,4,5,6,5,5]
#lista = [4,4]
rem(lista)

Output example:

rem([2, 4, 2, 4, 4])
[2, 4, 4]

The code works for the list [3,4,5,6,5,5] but not to [4,4]. What I did wrong?

2 answers

1

If you wanted to remove only 1 copy of each duplicated element, you can use one set and check whether you have "seen" this value or not:

def rem(lista):
    seen = set([])
    for i, x in enumerate(lista):
        if x in seen:
            lista.pop(i)
            break
        seen.add(x)
    return lista

lista = [3,4,5,6,5,5]
print(rem(lista))
#[3, 4, 5, 6, 5]
  • Your solution does not work as you only have to remove a duplicate copy. The output of (rem(list)) should be [3,4,6,5,5]

  • You want to remove only once each duplicate value?

  • that! Only one copy should be removed!

  • But at any specific position? You must remove the first duplicate or it may be the last?

  • could be anyone!

  • I don’t understand why they denied the question! I tried to do!

  • Okay, I didn’t realize it at first. Now look at the correction.

  • I didn’t understand some things in the code. Could you please comment?

  • Sure. What don’t you understand?

  • For example: Seen = set([])

  • This initializes the variable that will store the list elements as they are 'seen'. The type set is a type of object that does not allow duplicates.

  • Based on your answer, I tried to make a new code. What do you think of it?

Show 7 more comments

-1

def rem(lista):
    i = 0
    seen = set()
    nova_lista = lista.copy()
    while i < len(lista):
        # print(lista[i])

        if lista.count(lista[i]) >= 2:

            if lista[i] not in seen:
                nova_lista.remove(lista[i])
                seen.add(lista[i])


        i += 1
        print(f"seen :{seen}, nova_lista:{nova_lista}")
    print()
    print(nova_lista)


# lista = [3,4,5,6,5,5]
#lista = [4,4]
#lista = [3,4,5,6,5,5,5,6,6,3,6,4]
lista = [2,4,2,4,4]
rem(lista)
  • 2

    Explain the answer, please, otherwise it’s just a loose, meaningless code.

Browser other questions tagged

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