0

Can you tell me why my fundamental Python program doesn't run properly. First I have a isprime module:

def isPrime(value): 
    count = 0
    for i in range(1, value + 1): 
        if value % i == 0: 
            count += 1
    if count == 2: 
        return True
    else: 
        return False

and I import it to the PrimeFinder.py:

from isPrime import isPrime
lst = []
NumberOfValue = int(input())
for i in range(1, NumberOfValue + 1): 
    value = int(input())   
    lst.append(value)
for value in lst:
    if isPrime(value) == False: 
        lst.remove(value)
print(lst)

But when I input: the result also include non-prime numbers, can you explain if I was wrong in somewhere, thanks a lot for you help

  • for prime numbers, you need to find mod of i till values//2. For example to find if 17 is prime, you dont have to go all the way to 16. You just need to check between 2 and 8. Any value beyond 8 will result in 0.x – Joe Ferndz Jan 07 '21 at 06:18
  • 1
    You are trying to edit a list while iterating through it. This is discouraged. Take a look at the `filter` function as an alternative. – M Z Jan 07 '21 at 06:19
  • Why are you appending any number to the list instead of checking them beforehand? – OneCricketeer Jan 07 '21 at 06:19
  • 'cause of this line `lst.remove(value)`. Don't mutate the list while iterating. Small example `a = [1, 2]; for i in a: a.remove(i)` now `a` would still be `[2]`. – Ch3steR Jan 07 '21 at 06:19
  • OMG! thank you so much for all your help. I appreciate that – Digital Cat Jan 07 '21 at 06:22

2 Answers2

0
from isPrime import isPrime
lst = []
NumberOfValue = int(input())
for i in range(1, NumberOfValue + 1): 
    value = int(input())   
    if isPrime(value):
        lst.append(value)
print(lst)

Change the code to this, it will work. .remove will not remove the value from the list

SAI SANTOSH CHIRAG
  • 2,046
  • 1
  • 10
  • 26
0

Appears you should be doing

for i in range(1, NumberOfValue + 1): 
    value = int(input())   
    if isPrime(value):
        lst.append(value)

Otherwise, you're modifying a list while iterating, and therefore skipping over some indicies and leaving elements behind

Regarding the efficiency of your isPrime function, there are better ways isPrime Function for Python Language

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245