简体   繁体   中英

Returning True if perfect square/false if not

I'm doing an exercise on codewars and I'm supposed to find out if a number is a perfect square. I got the code done for the most part and it works most of the time, but when returning False, i get the wrong answer.

def is_square(n):  
    if n<0:
        return False
    if n == 0:
        return True
    if n>1:
        for i in range(0,n):
            if i*i==n:
                return True
            else:
                return False

If I remove the last else statement, 4 and 25 return true, but when I add in the last else statement, it says 4 and 25 are false. How would I go about fixing it so it returns false if 27 is entered while maintaining 25 to be true?

Put the return False after the for loop

def is_square(n):
    if n<0:
        return False
    if n == 0 or n == 1:
        return True
    if n > 1:
        for i in range(0,n):
            if i*i==n:
                return True
    return False

How would I go about fixing it so it returns false if 27 is entered while maintaining 25 to be true?

In your code the else statement:

            else:
                return False

is indented so that it the function returns False as soon as i*i doesn't equal n. You need to remove this "else" statement.

You should also add code to deal with n==1, for example

        if n==1:
            return True

You can finish up with a final "return False" at the lowest level of indentation in the function to catch the remainder of non-perfect squares.

You could also consider adding a check that i*i is less than or equal to n in the loop, this will greatly speed up your code when run on large numbers.

So, to sum up: Something like this code will work:

def is_square(n):  
    if n<0:
        return False
    if n == 0:
        return True
    if n == 1:
        return True
    if n>1:
        for i in range(0,n):
            if i*i==n:
                return True
    return False

But something like this code is better (faster):

def is_square(n):  
    if n<0:
        return False
    if n == 0:
        return True
    if n == 1:
        return True
    if n>1:
        for i in range(0,n):
            if i*i==n:
                return True
            if i*i>n:
                break
    return False

This should work:

def square(n):
    import math
    if (n < 0):
        return False
    if (int(math.sqrt(n)) == math.sqrt(n)):
        return True
    else:
        return False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM