Python完美正方形
我正在写一个函数,它以一个列表L作为参数,返回一个列表,该列表由L中的所有元素组成,这些元素都是完美的正方形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中
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
不返回列表。虽然此代码片段可以解决问题,但确实有助于提高文章质量。请记住,您将在将来回答读者的问题,这些人可能不知道您的代码建议的原因。还请尽量不要用解释性注释挤满你的代码,这会降低代码和解释的可读性!虽然这个代码片段可以解决这个问题,但它确实有助于提高文章的质量。请记住,您将在将来回答读者的问题,这些人可能不知道您的代码建议的原因。还请尽量不要用解释性注释挤满你的代码,这会降低代码和解释的可读性!