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 を返す 1 行のブール関数を書きたいと思います。

何かアドバイス?1行だけにする方法がわかりません。

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 に答える