Home > front end >  Problem selecting an item from the list in the loop
Problem selecting an item from the list in the loop

Time:11-12

def counter(x) :
    counter_list = []
    for i in range(2 , int(x**0.5)   1) :
        if x % i == 0 :
            counter_list.append(i)
    return counter_list

counter() check the counter of any number and return the counters as list

counter_list = counter(600851475143)
print(counter_list)

i get the counters of 600851475143 and I want to separate the prime numbers

for x in counter_list :
    #-----104441 is counter of 600851475143 but when But it is not placed in loop equal to the variable x, in other words, it is not read at all
    print("..////////////////////////////////////////////" , x)
    print(104441 in counter_list)
    for i in range(2 , int(x**0.5)   1) :

        if x % i == 0 :
            counter_list.remove(x)

My problem is that the number 104441 is in the list, but it is not read when it is used in a loop

CodePudding user response:

Try to create a copy of your list. If you don't do this, you are changing the list you are iterating over. This will cause the loop to behave in a wrong way.

# create a copy of your list
copy_counter_list = counter_list.copy()

for x in counter_list :
    #-----104441 is counter of 600851475143 but when But it is not placed in loop equal to the variable x, in other words, it is not read at all
    print("..////////////////////////////////////////////" , x)
    print(104441 in counter_list)
    for i in range(2 , int(x**0.5)   1) :

        if x % i == 0 :
            copy_counter_list.remove(x)

Your result will then be in copy_counter_list.

CodePudding user response:

You are looping over counter_list and remove values from this list in loop, you shouldn't do that.

Do:

>>> def counter(x) :
>>>     counter_list = []
>>>     for i in range(2 , int(x**0.5)   1) :
>>>         if x % i == 0 :
>>>             counter_list.append(i)
>>>     return counter_list
>>> counter_list = counter(600851475143)
>>> to_remove = []
>>> for x in counter_list :
>>>     for i in range(2 , int(x**0.5)   1) :
>>>         if x % i == 0 :
>>>             to_remove.append(x)
>>> for i in to_remove:
>>>     counter_list.remove(x)
>>> counter_list
[71, 839, 1471, 6857]
  • Related