寻找完美的广场

3zz*_*zzy 1 python

我有这个python代码:

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)
Run Code Online (Sandbox Code Playgroud)

输出是:

16 is not a perfect square.
Run Code Online (Sandbox Code Playgroud)

虽然这完美地运作:

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'
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Sun*_*rma 10

只是想我会贡献一个更简单的解决方案:

def is_square(n):
    return sqrt(n).is_integer()
Run Code Online (Sandbox Code Playgroud)

这是有效的n < 2**52 + 2**27 = 4503599761588224.

例子:

>>> is_square(4)
True
>>> is_square(123)
False
>>> is_square(123123123432**2)
True
Run Code Online (Sandbox Code Playgroud)


CMS*_*CMS 7

正确缩进代码以使while语句执行,直到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)
Run Code Online (Sandbox Code Playgroud)

在这里尝试一下.

  • 每天给我Python的缩进规则,因为我的缩进可能与C等人的大括号不符.如果确保编辑器仅配置为空格,则会更容易. (2认同)