Question

I have this following code for calculating prime numbers

def isPrime(n):
   if (n==2):
      return True
   elif n<=1 or n%2==0:
      return False
   else:
      for i in xrange(3,n/2, 2):
          if n%i:
            return False
   return True


mylist = [6,9]

mylist2= [3,5,7,11,12]

if not any(isPrime(x) for x in mylist):
       print "No primes in list"

if not all(isPrime(x) for x in mylist2):
       print "Not all are primes numbers"

when I run this program, I get

python calculate_primes.py 
Not all are primes numbers

I do not get the output of No primes in list. but if i remove element 9 in mylist and have only 6, it works fine.

python calculate_primes.py 
No primes in list
Not all are primes numbers

Either something wrong with my code or I am using the any wrongly? some tips here please

Était-ce utile?

La solution

There is something wrong with your isPrime() function. Within the for loop you are currently returning False if the condition n%i evaluates to True, but this will only happen if n is not evenly divisible by i. Instead you should be using if not n%i or if n%i == 0.

Autres conseils

You want if n%i == 0, not if n%i since i divides n only if the mod is 0. Your code is returning false when i does not divide n.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top