Python - Check if a number is a square

22,718

Solution 1

Your function doesn't actually work, as it will immediatley return False on the first non-square-root found. Instead you will want to modify your code to be:

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

such that it only returns false once all possible square roots have been checked. You may also want to look into math.sqrt() and float.is_integer(). Using these methods your function would become this:

from math import sqrt

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

Keep in mind that this method will not work with very large numbers, but your method will be very slow with them, so you will have to choose which to use. Hope I helped!

Solution 2

To stick to integer-based algorithms, you might look at implementation of binary search for finding square root:

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

Solution 3

The main idea of Python philosophy is to write simple code. To check if a number is an perfect square:

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

When power to a float you can find the root of a number.

Solution 4

You can simply use simpy module import it as,

from sympy.ntheory.primetest import is_square 

and you can check for a number like this:

is_square(number) 

It will return a boolean value

Share:
22,718
M. Abra
Author by

M. Abra

Updated on February 14, 2021

Comments

  • M. Abra
    M. Abra about 3 years

    I wrote a function that returns whether a number input is a square or not

    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
    

    I am confident that this code works. But when I did the test cases, example:test.expect( is_square( 4)), it says that the value is not what was expected.