is_prime potential false positive success


#1

This function is incorrect, it's using the for...else syntax that Python has, and just happens to pass the test numbers for testing. Can you confirm this is the case with more examples?

def is_prime(x):
    if x < 2:
        return False
    elif x == 2 or x == 3:
        return True
    else:
        for n in range(2, x-1):
            if x % n == 0:
                return False
        else:
                return True

#2

A list of primes shouldn't be very hard to find, figure out how to enter them into your program and then just compare that list to what your function says!

Here's a bunch.. https://primes.utm.edu/lists/small/10000.txt

It consists of a bunch of lines, each containing a couple of numbers..
So one would read the lines until there aren't any more
and for each line you would split it on whitespace and convert each
"word" into an integer.

Add all those integers to a set (a set supports constant-time checking of whether a
value exists in the set, whereas a list would have to iterate through itself, comparing
each of its elements to the value you are looking for) .. and then iterate through
numbers 0 up to the highest prime that you entered, if your function reports the number
to be a prime, then it should be in the set, and if not, then it shouldn't be there.

primes = set()
# Read numbers until an empty line is entered:
in_data = raw_input()
while in_data != "":
    # Convert in_data to integers and add them to the set
    primes.update(int(n) for n in in_data.split())
    in_data = raw_input()

And then you'd make a loop which iterates through 0 up to the highest prime you included in the user input:

for n in range(max(primes)+1):
    correct_answer = n in primes
    my_result = is_prime(n)
    if my_result == correct_answer:
        print 'my_result(%s) -> %s OK!' % (n, my_result)
    else:
        print 'my_result(%s) -> %s but correct answer is: %s' % (n, my_result, correct_answer)
        break