0

Hi guys, could you tell me how to solve this problem. This is what i've done.
The result show :
[9, 2, 6]
[3, 9, 5]

l1 = [4,9,2,6]
l2 = [3,9,4,5]
i = 0
j = 0

while(i < len(l1)):
    while(j < len(l2)):
        if(l1[i] == l2[j]):
            del(l1[i])
            del(l2[j])
        j += 1
    i += 1

print(l1)
print(l2)
3
Contributors
2
Replies
22
Views
1 Year
Discussion Span
Last Post by invisal
Featured Replies
  • 2

    Nice try. The reason that your code does not properly work is because when you delete a item in the list, you are decreasing the index of all the higher index by one then you increase the searching index by one also. So, you will skip some elements. To solve … Read More

2

Nice try. The reason that your code does not properly work is because when you delete a item in the list, you are decreasing the index of all the higher index by one then you increase the searching index by one also. So, you will skip some elements.

To solve this, you need to do it the reverse order.

l1 = [4,9,2,6]
l2 = [3,9,4,5]

i = len(l1) - 1
while(i >= 0):
    j = len(l2) - 1
    while(j >= 0):
        if (l1[i] == l2[j]):
            del(l1[i])
            del(l2[j])
        j -= 1
    i -= 1

print(l1)
print(l2)

However, there is still flaw in this code. For example, [9, 9, 1] and [2, 9]. The first list has more number 9 than the second list. The above code will only remove one 9. There is slightly better way to do this using dictionary to decide which number is duplicated in both list and remove later.

l1 = [4,9,9,2,6]
l2 = [3,9,4,5]
d = {}

for x in l1:
    d[x] = d.get(x, 0) | 1

for x in l2:
    d[x] = d.get(x, 0) | 2

l1 = [x for x in l1 if d.get(x,0) != 3]
l2 = [x for x in l2 if d.get(x,0) != 3]

print(l1)
print(l2)

Edited by invisal

Votes + Comments
Thank you for the quick replay. I learn something new from you (using dictionary)
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.