-3

the code is basically input two list and comparing each other letter-wise and if it doesn't find the letter in both words then it removes that letters but it my case once the first letter(i.e.not found in both words) is removed, it exits the loops why so

    a = input()
    b = input()
    al = list(a)
    bl = list(b)
    cnt = 0
    for x in al:
        if x not in bl:
            al.remove(x)
            cnt = cnt + 1
NevetsKuro
  • 604
  • 7
  • 14

1 Answers1

1

It does finish the for loop because you are making a change in the list during runtime and simultaneously you are iterating over it, this means

When letter a in al list is not found in bl list it will be removed from the al list,now the list will be ['b','c'] now in the for loop ie for x in al meant to be the second element of the list so the second element of the list is 'c' and it is in the list bl so there is no other element in al to iterate over so it comes out of the loop

In order to do so you can use a temp list to remove so that it won't affect the real list

a = input()
b = input()
al = list(a) 
bl = list(b)
temp_a = al.copy()
cnt = 0
for x in al:
    if x not in bl:
        temp_a.remove(x)
        cnt = cnt + 1
print(temp_a)

Output:
['c']
DaVinci
  • 868
  • 1
  • 7
  • 25