簡體   English   中英

Python - 檢查數字是否為正方形

[英]Python - Check if a number is a square

我寫了一個 function 返回數字輸入是否為正方形

def is_square(n):
    if n<1:
        return False
    else:
        for i in range(int(n/2)+1):
            if (i*i)==n:
                return True
            else:
                return False

我相信這段代碼有效。 但是當我做測試用例時,例如: test.expect( is_square( 4)) ,它說這個值不是預期的。

您的函數實際上不起作用,因為它會在找到的第一個非平方根上立即返回 False。 相反,您需要將代碼修改為:

def is_square(n):
    if n<1:
        return False
    else:
        for i in range(int(n/2)+1):
            if (i*i)==n:
                return True
        return False

這樣它只有在檢查了所有可能的平方根后才返回 false。 您可能還想查看math.sqrt()float.is_integer() 使用這些方法你的函數會變成這樣:

from math import sqrt

def is_square(n):
    return sqrt(n).is_integer()

請記住,此方法不適用於非常大的數字,但您的方法會非常慢,因此您必須選擇使用哪個。 希望我有所幫助!

要堅持基於整數的算法,您可能會查看二進制搜索的實現以找到平方根:

def is_square(n):
    if n < 0:
        return False
    if n == 0:
        return True
    x, y = 1, n
    while x + 1 < y:
        mid = (x+y)//2
        if mid**2 < n:
            x = mid
        else:
            y = mid
    return n == x**2 or n == (x+1)**2

Python哲學的主要思想是編寫簡單的代碼。 要檢查數字是否為完全平方數:

def is_square(n):
    return n**0.5 == int(n**0.5)

當為浮點數供電時,您可以找到數字的根。

您可以簡單地使用 simpy 模塊將其導入為,

from sympy.ntheory.primetest import is_square 

你可以檢查這樣的數字:

is_square(number) 

它將返回一個布爾值

def myfunct(num):
    for i in range(0,num):
        if i*i==num:
            return 'square'
    else:
        return 'not square'

最簡單的工作解決方案,但不適用於大量。

def squaretest(num):
    sqlist=[]
    i=1
    while i**2 <= num:
        sqlist.append(i**2) 
        i+=1
    return num in sqlist

假設 n >= 0:

def is_square(n):
    tmp = int(n ** 0.5)
    return n == tmp * tmp
          
print(is_square(81), is_square(67108864 ** 2 + 1))  # True False

另一種方法:

    def SQRT(x):
        import math
        if math.sqrt(x) == round(math.sqrt(x)):
            return True
        else:
            return False
def is_square(n):
if n< 0:
    return False
return round(n ** 0.5) ** 2 == n

在 Python 3.8+ 中,使用這個:

def is_square(n):
    root = math.isqrt(n)
    return n == root * root

我認為僅使用“內置”integer 算術的最佳方法是:

def issquare(n): return math.isqrt(n)**2==n

(平方 x**2 比乘積 x*x 更有效地計算......)

根據我的時間安排,這比sympy.numtheory.primetest.is_square快(至少高達 ~ 10^8)。

(我使用不同的名稱以便更容易比較兩者。)后者首先使用一些模塊化檢查,應該可以大大加快速度,但它有太多的轉換和測試開銷( intas_int , squares 成為第 n 個n = 2 的冪,整數從“小”轉換為多精度整數並返回,......)所有優勢都丟失了。 經過大量測試,它大致完成了上述操作,使用 ntheory.nthroot,這又是一個大材小用:為任何 n 次根設計,平方根只是一種特殊情況,注意針對這種情況進行了優化。 那里的一些子程序甚至會做非常奇怪的浮點運算,包括與 1.0000000001 的乘法和類似的恐怖……我曾經收到以下可怕的錯誤消息:(原始 output 具有完整路徑"C:\Users\Username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\"而不是下面的每個“...”...)

  File "...\sympy\ntheory\primetest.py", line 112, in is_square
    return integer_nthroot(n, 2)[1]
  File "...\sympy\core\power.py", line 86, in integer_nthroot
    return _integer_nthroot_python(y, n)
  File "...\sympy\core\power.py", line 94, in _integer_nthroot_python
    x, rem = mpmath_sqrtrem(y)
  File "...\mpmath\libmp\libintmath.py", line 284, in sqrtrem_python
    y = isqrt_small_python(x)
  File "...\mpmath\libmp\libintmath.py", line 217, in isqrt_small_python
    r = int(x**0.5 * 1.00000000000001) + 1
KeyboardInterrupt

這很好地說明了sympyis_square無可救葯地淹沒的深淵......

文檔:參見is_square的 Ntheory Class 參考中的 is_square

PS:FWIW,關於建議使用round()等的其他答案,讓我在這里提一下ceil(sqrt(n))**2 < n (,,),例如當 n 是第 26 和第 27 個原始元素時——不是特別大的數字! 所以,很明顯,使用math.sqrt是不夠的。

要檢查數字是否為正方形,您可以使用如下代碼:

import math
number = 16
if math.sqrt(number).is_interger:
        print "Square"
else:
        print "Not square"

import math import s math模塊。

if math.sqrt(number).is_interger:檢查number平方根是否為整數。 如果是這樣,它將print Square 否則,它將print Not square

由於 math.sqrt() 返回一個浮點數,我們可以將它轉換為一個字符串,將它從“.”中拆分出來。 並檢查右邊的部分(小數點)是否為 0。

import math
def is_square(n):
x= str(math.sqrt(n)).split(".")[1]  #getting the floating part as a string.
return True if(x=="0") else False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM