寻找完全平方数
我有一段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)
运行结果是:
16 is not a perfect square.
而这段代码运行得很好:
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'
我哪里出错了?
9 个回答
1
你的 while
循环只会执行一次。无论里面的 if
语句走哪条路,整个函数都会立刻返回。
10
我想分享一个更简单的解决方案:
def is_square(n):
return sqrt(n).is_integer()
这个适用于 n < 2**52 + 2**27 = 4503599761588224
。
举个例子:
>>> is_square(4)
True
>>> is_square(123)
False
>>> is_square(123123123432**2)
True
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)
你可以在 这里试试看。