开发者

Finding perfect square

开发者 https://www.devze.com 2022-12-08 18:26 出处:网络
I have this python code: def sqrt(x): ans = 0 if x >= 0: while ans*ans < x: ans = ans + 1 if ans*ans != x:

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?


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


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.


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


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.


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


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


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


I think this is probably short.

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


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))
0

精彩评论

暂无评论...
验证码 换一张
取 消