Ahmed Adel
Ahmed Adel

Reputation: 49

Need to remove all duplicated values in list

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!!`

Upvotes: 2

Views: 123

Answers (5)

Nawal
Nawal

Reputation: 336

Edit This is NOT correct solution of the above problem. It removes contiguous duplicates from the list. But in question, we need to keep 1 instance of duplicate element.

Please refer to @funnydman solution. Thanks @funnydman for pointing out the mistake :)


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])

Upvotes: 3

josix
josix

Reputation: 1

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, 2, 3]) == [3]
assert deduplicate([2, 2, 2]) == []
assert deduplicate([2, 2, 2, 3]) == [3]

Upvotes: 0

funnydman
funnydman

Reputation: 11346

Unfortunately, Nawal's solution does not produce the correct answer, I would suggest this approach:

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]

Upvotes: 2

Samwise
Samwise

Reputation: 71464

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]

Upvotes: 5

JJaco
JJaco

Reputation: 61

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)

Upvotes: 1

Related Questions