0

First time poster here, so I sincerely apologize if this question is not adequately posited (and the shear stupidity of the question)

I am given a list of possible primes -- it has already accounted for any numbers with single digit factors (i.e., 2, 3, 5, 7) -- and I am to return the remaining primes in a list. Here is what I currently have:

def find_the_prime(list_of_possibles):
    for num in list_of_possibles:
        for j in range(2, num):
            if num % j == 0:
                list_of_possibles.remove(num)
            return list_of_possibles
result = find_the_prime(possible_primes)
print(result)

I am aware that the return condition is misplaced as this terminates the loop. However, if the return function is repositioned anyway, I get the following ValueError: "list.remove(x): x not in list". I am sure the equation is correct for locating/identifying a prime, as I can use the equation in a simple for loop and directly implement a number. But when I try to iterate through the provided list I am having issues.

Any assistance would be greatly appreciated. Thank you in advance.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • You are modifying a list as you iterate through it. That is the problem. The `for` loop remembers where it was in the list, but because you have removed things, the list is now shorter. Instead of this, you should create a NEW list that only contains the numbers you want to keep. – Tim Roberts Sep 17 '22 at 00:55
  • It's good to train yourself to work inwards. e.g. `def filterPrimesFrom(cands): return [u for u in cands if isPrime(u)]`. This way you've blackboxed a 'thing' that has clear input/function/output, which you can now figure out. – P i Sep 17 '22 at 01:08
  • @TimRoberts: It's not *just* modifying the `list` as they go. They try to `remove` `num` once for each value it's divisible by. So any number with multiple divisors (which is all non-primes, since they test from `2` to `num`) gets removed twice for each time it occurs. – ShadowRanger Sep 17 '22 at 01:15

0 Answers0