-1

I am working on a leetcode question. i'm Trying to make sure that each element in list g matches with one element of list s , where each integer number of list g is equal to or less than integer number of list s. In the below loop, somehow, it skipped number 2 from list s.

Here is the output:

1
1
index0
1
3
index1
2
2
index0
0

the source code:

g = [1,2]
s = [1,2,3]

count = 0
g = sorted(g)
s = sorted(s)

for x in g:
  for y in s:
    if x <= y:
      print(x)
      print(y)
      index = s.index(y)
      print("index" + str(index))
      del s[index]

print(count)
Signor
  • 467
  • 2
  • 8
  • 21

1 Answers1

0

it's generally considered a pretty bad idea to modify either an iterator or a collection being iterated over from within a loop. you delete from the s and then try to reference s[1] behind the scenes. (new_s = [2,3] ). and y now ignore the first element that is 2.

but s[1] is now 3, not 2 as you expect, because you have modified the s with del s[index].

Signor
  • 467
  • 2
  • 8
  • 21