2

我编写了这个 python 函数,它接受一个列表作为参数,并确定列表中的哪些元素是完美的正方形,然后返回一个仅包含这些选择元素的新列表。

这是我的功能:

def square(n):
    return n**2

def perfectSquares1(L):
    import math
    m=max(L)
    for n in L:
        if type(n) is int and n>0:
            Result=map(square,range(1,math.floor(math.sqrt(m))))
            L1=list(Result)
    L2=list(set(L).intersection(set(L1)))
    return L2

但现在我正在尝试对其进行一些修改:我想编写一个单行布尔函数,它以 n 作为参数,如果 n 是一个完美的正方形则返回 True,否则返回 false。

有什么建议吗?我想不出一种方法让它只有一条线。

4

3 回答 3

6
lambda n: math.sqrt(n) % 1 == 0
于 2013-07-07T03:02:39.487 回答
3

你可以做:

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

或者您可以使用:

import math
def perfect_sq(n):
    return n == int(math.sqrt(n)) ** 2
于 2013-07-07T03:02:05.873 回答
1

可以使用模运算符:

>>> def perfectsquare(n):
...     return not n % n**0.5
...
>>> perfectsquare(36)
True
>>> perfectsquare(37)
False
>>> perfectsquare(25)
True
>>> perfectsquare(4215378*4215378)
True
于 2013-07-07T03:04:17.620 回答