Is_Prime Question


#1

Hi All:
My code is below for is_prime - it keeps breaking on is_prime(2), but 2 is pretty clearly broken out. However, is_prime(2) is returning False instead of True.

def is_prime(x):
if x<2 or x is not int:
return False
if x==2:
return True
if x>2:
for n in range (2,x):
if x%n==0:
return False
else:
return True


#2

>>> x = 1.2
>>> x is not int
True
>>> x is float
False
>>> x = 1
>>> x is not int
True
>>>

What this demonstrates is that this logic is not working for us as expected. We need to be a bit more explicit...

>>> x = 1
>>> type(x) is not int
False
>>> type(x) != int
False
>>> x = 1.2
>>> type(x) is not int
True
>>> type(x) != int
True
>>>

Of course this test will leak booleans as a 1 or a 0 so they need to be trapped as well (if you're going to have this test work correctly).

>>> x = 1.2
>>> type(x) is not int or type(x) is bool or x < 2
True
>>> x = True
>>> type(x) is not int or type(x) is bool or x < 2
True
>>> x = 1
>>> type(x) is not int or type(x) is bool or x < 2
True
>>> x = 3
>>> type(x) is not int or type(x) is bool or x < 2
False
>>>

For our purposes the test is not required.

if x < 2:

is ample enough. But you are thinking intuitively, which is a great indication.

Consider the range of your loop: range(2, x). Will it execute when x == 2? No. 2 bypasses the loop. Hence there is no need for else.

return True

or the above lines.


#3

Thanks! But can you explain why the simply x==2 return True doesn't make is_prime(2) return True?

Thanks.


#4

Because the logic is slightly flawed above that line. It never gets to the line,

if x == 2:

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.