Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.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,我正在写一个函数,它以一个列表L作为参数,返回一个列表,该列表由L中的所有元素组成,这些元素都是完美的正方形 def isPerfectSquare(n): return n==int(math.sqrt(n))**2 def perfectSquares2(L): import math return(list(filter(isPerfectSquare,(L)))) 我认为我的过滤功能是错误的,但我不知道如何修复它 您必须在isPerfectSquare中

我正在写一个函数,它以一个列表L作为参数,返回一个列表,该列表由L中的所有元素组成,这些元素都是完美的正方形

def isPerfectSquare(n):

    return n==int(math.sqrt(n))**2


def perfectSquares2(L):

    import math
    return(list(filter(isPerfectSquare,(L))))

我认为我的过滤功能是错误的,但我不知道如何修复它

您必须在
isPerfectSquare
中导入数学,否则它只是在
perfetSquares2
函数的本地范围内导入

但是,建议您将模块导入放在脚本的顶部:

import math
def isPerfectSquare(n):
    return n==int(math.sqrt(n))**2

def perfectSquares2(L):
    return(list(filter(isPerfectSquare,(L))))

顺便说一句,我认为在这里列表理解可能更快:

def perfectSquares2(L):
    return [i for i in L if isPerfectSquare(i)]

您必须在
isPerfectSquare
中导入数学,否则它只是导入到
perfetSquares2
函数的本地范围内

但是,建议您将模块导入放在脚本的顶部:

import math
def isPerfectSquare(n):
    return n==int(math.sqrt(n))**2

def perfectSquares2(L):
    return(list(filter(isPerfectSquare,(L))))

顺便说一句,我认为在这里列表理解可能更快:

def perfectSquares2(L):
    return [i for i in L if isPerfectSquare(i)]

这是使用
lambda
的好地方。另外,如果使用Python2.x或其他参数,则无需使用
list()

import math
def perfectSquares2(L):
    return filter(lambda n: n==int(math.sqrt(n))**2, L)

这是使用
lambda
的好地方。另外,如果使用Python2.x或其他参数,则无需使用
list()

import math
def perfectSquares2(L):
    return filter(lambda n: n==int(math.sqrt(n))**2, L)

什么使你认为它错了?
math.sqrt
是近似值,所以当你达到浮点精度限制时,平方检查将失败。什么使你认为它错了?
math.sqrt
是近似值,所以当你达到浮点精度限制时,平方检查将失败。在Python 3中,
filter
不返回列表。在Python 3中,
filter
不返回列表。虽然此代码片段可以解决问题,但确实有助于提高文章质量。请记住,您将在将来回答读者的问题,这些人可能不知道您的代码建议的原因。还请尽量不要用解释性注释挤满你的代码,这会降低代码和解释的可读性!虽然这个代码片段可以解决这个问题,但它确实有助于提高文章的质量。请记住,您将在将来回答读者的问题,这些人可能不知道您的代码建议的原因。还请尽量不要用解释性注释挤满你的代码,这会降低代码和解释的可读性!