Why does my while loop skip an item in my list?

I have a list of integers that I run through a for loop to detect if two of the combined elements are equal to another variable t . So if t was equal to 10 , and I had a list of intergers: l = [1,2,3,4,5,8,9] , then the function should print all the different combinations of numbers (1,9) , (2,8) .

I feel like I'm almost there, but something strange happens to the list when I use the .pop() function. The code below is used to display all combinations of numbers that need to be calculated, but every other item in the list is skipped.

 l = [1,2,5,8,13,15,26,38] c = 10 for i in l: first = i l.pop(0) for x in l: second = x print(first,second) 

Here is the result:

 1 2 1 5 1 8 1 13 1 15 1 26 1 38 5 5 5 8 5 13 5 15 5 26 5 38 13 8 13 13 13 15 13 26 13 38 26 13 26 15 26 26 26 38 

Please note that tags 2 , 8 , 15 and 38 skipped. I use l.pop , so the second for loop will not use the original value, and the next iteration can continue to iterate the next item in the list.

+5
source share
2 answers

What you are trying to do will not work, as you are modifying the list during iteration. Say the current "pointer" points to the first element. Now you select the first, so the pointer is on the second. But when the loop advances, the pointer moves to the third, and the second is skipped.

It seems you want to find combinations from the list. There are several other ways you can try:

  • Closer to your current approach: use a while instead of for loop

     while l: first = l.pop(0) for second in l: print(first, second) 
  • Or you could just iterate over the indexes instead of the lists themselves:

     for i in range(len(l)): for k in range(i+1, len(l)): print(l[i], l[k]) 
  • Or just use itertools.combinations

     import itertools for first, second in itertools.combinations(l, 2): print(first, second) 

However, you can do better than that. Since you are looking for a pair of numbers that are added to some target number, simply subtract the first from the target to get the second and see if this second number is on the list of numbers. Use set to have this search run in constant time, reducing the overall time complexity from O (nΒ²) to O (n).

 numbers = set([1,2,5,8,13,15,26,38]) target = 10 for first in numbers: second = target - first if second > first and second in numbers: print(first, second) 
+9
source

you need to choose a different approach. You are not allowed to remove items from the list, iterating over it using a for loop.

0
source

Source: https://habr.com/ru/post/1234525/


All Articles