Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中检查数字是否是列表中的质数_Python_Python 3.x - Fatal编程技术网

在Python中检查数字是否是列表中的质数

在Python中检查数字是否是列表中的质数,python,python-3.x,Python,Python 3.x,我已经编写了以下代码,应该检查列表中的数字是否为素数,但有一个问题我无法解决,因为我正在尝试实现对num平方根的检查优化,我有一个类型错误 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 s

我已经编写了以下代码,应该检查列表中的数字是否为素数,但有一个问题我无法解决,因为我正在尝试实现对num平方根的检查优化,我有一个类型错误

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)
def为素数(x):
如果x
x**(0.5)+1
不是整数,那么
range
无法生成列表

尝试四舍五入:

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)
从数学导入单元
def是_素数(x):
如果x
x**(0.5)+1
不是整数,那么
range
无法生成列表

尝试四舍五入:

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)
从数学导入单元
def是_素数(x):
如果x表达式:

range(3, x**(0.5)+1, 2):
升级为浮点类型,因为

x**(0.5)
对于所需的行为,需要再次将其设置为int,请尝试:

range(3, int(round(x**(0.5)+1)), 2):
在哪里

告诉python您希望将x解释为整数类型

返回与x最接近的整数

请注意,舍入可能不是您所期望的:

表达式:

range(3, x**(0.5)+1, 2):
升级为浮点类型,因为

x**(0.5)
对于所需的行为,需要再次将其设置为int,请尝试:

range(3, int(round(x**(0.5)+1)), 2):
在哪里

告诉python您希望将x解释为整数类型

返回与x最接近的整数

请注意,舍入可能不是您所期望的:

如果列表中的某个数字是素数,则检查该数字,并将该素数附加到列表中。


如果列表中的某个数字是素数,请检查该数字,并将该素数附加到列表中。

范围
仅将
int
s(或
)作为参数。
x**(0.5)+1的结果是一个
float
。。。这应该足以提示您找出剩余的
范围
仅将
int
s(或
None
)作为参数。
x**(0.5)+1的结果是一个
float
。。。这应该是一个足够的提示,让你明白剩下的