Danny Danny - 4 years ago 116
Python Question

Checking if a number is a prime number from a list, in Python

I have written the following code, which should check if the numbers in the list is a prime number or not, but there is an issue I couldn't get through, as I am trying to implementing the optimization of check up to the square root of num, I have a type error.

def is_prime(x):
if x <= 1:
return False
if x == 2:
return True
for n in range(3, x**(0.5)+1, 2): # this skips even numbers and only checks up to sqrt(x)
if x % n == 0:
return False
return True


my_list = [1,2,4,5,6,7]
result = list(map(is_prime,my_list))

print(result)





File "PrimeCheck.py", line 39, in <module>
result = list(map(is_prime,my_list))
File "PrimeCheck.py", line 32, in is_prime
for n in range(3, x**(0.5)+1, 2): # this skips even numbers and only checks up to sqrt(x)
TypeError: 'float' object cannot be interpreted as an intege

Answer Source

x**(0.5)+1 is not an integer, so range can't generate the list.

Try rounding up:

from math import ceil
def is_prime(x):

    if x <= 1:
        return False
    if x == 2:
        return True
    for n in range(3, ceil(x**(0.5)), 2):   # this skips even numbers and only checks up to sqrt(x)
        if x % n == 0:
            return False
    return True


my_list = [1,2,4,5,6,7]
result = list(map(is_prime,my_list))

print(result)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download