0

I am deleting the common elements between 2 sorted arrays in both the arrays and returning the arrays with the help of 2 pointers. But I can't figure out the condition in while loop: what should be the condition?

here is my code:

a=[4,8,9,10,12,14,16]
b=[2,8,10,12,13]
i=0
j=0
while():
     if (a[i]==b[j]):
      a.pop(i)
      b.pop(j)
    elif(a[i] > b[j]):
      j=j+1
    else:
      i=i+1
print(a)
print(b)
Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
anadi
  • 63
  • 1
  • 6

3 Answers3

0

Your while loop should be running until variable i is less than len(a) and variable j is less than len(b).

Since you have missed some part of your list a, I tried to run your code with 13 as the last element.

NOTE:

The code will only work if both lists are sorted.

a=[4,8,9,10,13]
b=[2,8,10,12,13]
j=0
i = 0
while i < len(a) and j < len(b):
        if (a[i]==b[j]):
                a.pop(i)
                b.pop(j)
        elif(a[i] > b[j]):
                j=j+1
        else:
                i=i+1
print(a)
print(b)

Output:

[4, 9]
[2, 12]

You can also try the code below. It is more readable and doesn't require the lists to be sorted. It uses list comprehension.

a1 = [x for x in a if x not in b]
b1 = [x for x in b if x not in a]
abhiarora
  • 9,743
  • 5
  • 32
  • 57
  • b = [x for x in b if x not in a] is printing wrong results for b – anadi Dec 23 '19 at 10:26
  • Try again. I have edited my answer. Use `b = [x for x in b if x not in a]` not `b = [x for x in a if x not in a]`. – abhiarora Dec 23 '19 at 10:27
  • @abhiarora, you have already modified `a` with first list comprehension. so the second one will not work and `b` will remain unchanged. You may want to save them in different variable – kuro Dec 23 '19 at 10:29
  • @kuro. Right! Thanks for pointing it out. @anadi. Try again with the following:`a1 = [x for x in a if x not in b]; b1 = [x for x in b if x not in a]` – abhiarora Dec 23 '19 at 10:30
  • @anadi The problem was I was overwriting the list `a` in the first statement and hence the second statement had a different copy of `b` and `a`. – abhiarora Dec 23 '19 at 10:32
0
a=[2,3,4,7,9]
b=[3,5,6,8,9]

dup = []
for x in a:
    if x in b:
        dup.append(x)

for x in dup:
    a.remove(x)
    b.remove(x)

print(a)

Create a duplicate elements list and then remove the duplicate elements from both A and B.

Strange
  • 1,460
  • 1
  • 7
  • 18
0

The while loop does not have exit criteria. Ideally it should be part of while(cond). Or, it should be a conditional break in the while block

a=[4,8,9,10,12,14,16]
b=[2,8,10,12,13]
i=0
j=0

while i < len(a) and j < len(b):
    if a[i] == b[j]:
      print("Deleting duplicate ", a[i])
      a.pop(i)
      b.pop(j)
    elif a[i] > b[j]:
      j=j+1
    else:
      i=i+1

print(a, b)
pr-pal
  • 3,248
  • 26
  • 18