accelerate
accelerate

Reputation: 51

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?

Upvotes: 0

Views: 2289

Answers (3)

PotatoLatte
PotatoLatte

Reputation: 83

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

Upvotes: 0

J. Owens
J. Owens

Reputation: 852

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

Upvotes: 3

hft
hft

Reputation: 1245

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

Upvotes: 0

Related Questions