Issue
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 number, I have a TypeError
.
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 integer
Solution
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)
Answered By - asiviero
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.