Home > database >  Need to remove all duplicated values in list
Need to remove all duplicated values in list

Time:08-07

I am trying to solve this question "Good array is the array that does not contain any equal adjacent elements. Given an integer array A of length N, you are asked to do some operations (possibly zero) to make the array good. One operation is to remove two equal adjacent elements and concatenate the rest of the array. A : (1, 2, 2, 3, 4) An after-one operation : (1, 3, 4) " With python list, as follow:

L=[]
n=int(input("Enter a num"))
for _ in range(n):
    x=int(input())
    L.append(x)    
print(L)
for z in range(L):
    if L[z]==L[z 1]
    L.remove(z)
    L.remove(z 1)
print(L).

I keep getting this error: Input In [37] if L[z]==L[z 1] ^ SyntaxError: invalid syntax any solutions!!`

CodePudding user response:

Easiest solution is to groupby the array and just keep the groups with only one item:

>>> A = [1, 2, 2, 3, 4]
>>> import itertools
>>> A = [i for i, g in itertools.groupby(A) if len(list(g)) == 1]
>>> A
[1, 3, 4]

CodePudding user response:

You are iterating the list and deleting items from the same :| Not a good idea!

You can use another list to store the result.

result = []
for z in range(len(L)-1):
    if L[z]!=L[z 1]:
        result.append(L[z])
result.append(L[-1])

CodePudding user response:

Unfortunately, the most voted answer does not produce the correct answer (and has TypeError), I would suggest this solution:

def get_good_array(alist):
    result = []
    L = alist   [None]
    i = 0
    while i < len(L) - 1:
        if L[i] != L[i   1]:
            result.append(L[i])
            i  = 1
        else:
            i  = 2
    return result


assert get_good_array([1, 2, 2, 3, 4]) == [1, 3, 4]
assert get_good_array([1, 1, 2, 2, 3, 4]) == [3, 4]
assert get_good_array([0, 1, 1, 2, 2, 3, 4]) == [0, 3, 4]
assert get_good_array([1, 3, 4, 4]) == [1, 3]
assert get_good_array([1, 3, 4, 4, 5]) == [1, 3, 5]

CodePudding user response:

You are missing a : at the end of the if statement, your code should look like the following

L=[]
n=int(input("Enter a num"))
for _ in range(n):
    x=int(input())
    L.append(x)    
print(L)
for z in range(L):
    if L[z]==L[z 1]:
        L.remove(z)
        L.remove(z 1)
print(L)

CodePudding user response:

I guess using <list>.count() is quite intuitive approach. As following,

def deduplicate(l: list):
    return [value for value in l if l.count(value) == 1]

assert deduplicate([2]) == [2]
assert deduplicate([2, 2]) == []
assert deduplicate([2, 3, 2]) == [3]
assert deduplicate([2, 2, 2]) == []
assert deduplicate([2, 2, 2, 3]) == [3]
  • Related