eozzy
eozzy

Reputation: 68650

Finding perfect square

I have this python code:

def sqrt(x):
    ans = 0
    if x >= 0:
        while ans*ans < x:
            ans = ans + 1
            if ans*ans != x:
                print x, 'is not a perfect square.'
                return None
            else:
                print x, ' is a perfect square.'
                return ans
    else:
        print x, ' is not a positive number.'
        return None

y = 16      
sqrt(y)

the output is:

16 is not a perfect square.

Whereas this works perfectly:

x = 16
ans = 0
if x >= 0:
    while ans*ans < x:
        ans = ans + 1
        #print 'ans =', ans
    if ans*ans != x:
        print x, 'is not a perfect square'  
    else: print ans, 'is a perfect square'
else: print x, 'is not a positive number'

What am I doing wrong?

Upvotes: 2

Views: 20214

Answers (9)

Suman Michael
Suman Michael

Reputation: 11

I think this is probably short.

 def issquare():
      return (m**.5 - int(m**.5)==0)

Upvotes: 0

Sunjay Varma
Sunjay Varma

Reputation: 5115

Just thought I'd contribute a simpler solution:

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

This is valid for n < 2**52 + 2**27 = 4503599761588224.

Examples:

>>> is_square(4)
True
>>> is_square(123)
False
>>> is_square(123123123432**2)
True

Upvotes: 10

trycatch22
trycatch22

Reputation: 327

def isPerfectSquare(number):
    return len(str(math.sqrt(number)).split('.')[1]) == 1

Upvotes: 0

gumption
gumption

Reputation: 1128

If the goal is to determine whether a number is a perfect square, I would think it would be simpler (and perhaps more efficient) to use math builtins, e.g.:

def is_perfect_square(n):
  if not ( ( isinstance(n, int) or isinstance(n, long) ) and ( n >= 0 ) ):
    return False 
  else:
    return math.sqrt(n) == math.trunc(math.sqrt(n))

Upvotes: -1

ManicMailman
ManicMailman

Reputation: 75

EDIT I modified it, tried it out, and it works. You just need this piece of code

As soon as ans = 4, ans * ans is no longer smaller than x. Try while ans*ans <= x: instead of just <

def sqrt(x):
ans = 0
if x >= 0:
        while ans*ans <= x:                     
                if ans*ans == x:
                            print x, ' is a perfect square.'
                            return ans
        else:
            ans = ans + 1

Upvotes: 0

stiank81
stiank81

Reputation: 25686

If your code sample is actually correctly indentet the first round of the while will return on it's first round - always. So any positive value of x>1 will fullfil the ans*ans=1*1=1!=x, giving "x is not a perfect square".

You basically needs to get your indentation right - like you do in your other example. Again - if your code sample here actually is correctly indented. Try this:

def sqrt(x):
    ans = 0
    if x >= 0:
        while ans*ans < x:
            ans = ans + 1

        if ans*ans != x:
            print x, 'is not a perfect square.'
            return None
        else:
            print x, ' is a perfect square.'
            return ans
    else:
        print x, ' is not a positive number.'
        return None

Upvotes: 0

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827256

Indent your code correctly to let the while statement execute until ans*ans < x:

def sqrt(x):
    ans = 0
    if x >= 0:
        while ans*ans < x:
            ans = ans + 1

        if ans*ans != x:  # this if statement was nested inside the while
            print x, 'is not a perfect square.'
            return None
        else:
            print x, ' is a perfect square.'
            return ans
    else:
        print x, ' is not a positive number.'
        return None

y = 16          
print sqrt(y)

Try it out here.

Upvotes: 7

pavium
pavium

Reputation: 15118

Change your code so it displays the value of ans as well as x, so you can tell how many times the loop is executed.

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 992887

Your while loop only executes once. No matter which branch the if statement inside it takes, the whole function will return immediately.

Upvotes: 1

Related Questions