问题描述
这是我的代码,但是它只返回下一个数字(例如,取 121 它返回 122 而不是 144),但我不明白为什么。
import math
def find_next_square(sq):
# Return the next square if sq is a square,-1 otherwise
if math.sqrt(sq).is_integer:
sqnext = sq + 1
if math.sqrt(sqnext).is_integer:
return sqnext
else:
return -1
解决方法
你的逻辑不正确。使用 sqnext = sq + 1
,您计算的是下一个数字,而不是下一个平方。
试试这个:
import math
def find_next_square(sq):
# Return the next square if sq is a square,-1 otherwise
if math.sqrt(sq).is_integer:
sqnext = math.sqrt(sq) + 1
return sqnext * sqnext
else:
return -1
print(find_next_square(121))
编辑
看起来 is_integer
方法有缺陷并且给出了 Henry 指出的错误值。以下代码适用于达到特定限制的正整数。
import math
def find_next_square(sq):
# Return the next square if sq is a square,-1 otherwise
if int(math.sqrt(sq))**2 == sq:
sqnext = math.sqrt(sq)
return sqnext * sqnext
else:
return -1
print(find_next_square(5))
print(find_next_square(121))
此外,由于 sqrt
不适用于负数,因此需要单独处理:
import math
def find_next_square(sq):
# Return the next square if sq is a square,-1 otherwise
sign = -1 if sq < 0 else 1
if int(math.sqrt(abs(sq)))**2 == abs(sq):
sqnext = math.sqrt(abs(sq)) + sign * 1
return sqnext * sqnext * sign
else:
return -1
print(find_next_square(5))
print(find_next_square(121))
print(find_next_square(-9))
此外,由于溢出问题,上述所有方法都不适用于超出限制的大量数字。
,在 sqnext = sq + 1
中,您将前一个数字的平方加 1 并将其分配给 sqnext
。
应该是sqnext = (math.sqrt(sq)+1)**2
import math
def find_next_square(sq):
# Return the next square if sq is a square,-1 otherwise
if math.sqrt(sq).is_integer:
sqnext = (math.sqrt(sq)+1)**2
return sqnext
else:
return -1
,
import math
def find_next_square(sq):
# Return the next square if sq is a square,-1 otherwise
if math.sqrt(sq).is_integer:
sqnext = math.sqrt(sq) + 1
if math.sqrt(sqnext).is_integer:
return int(sqnext * sqnext)
else:
return -1
sqnext = sq + 1
这就是你错的地方。您应该返回 math.sqrt(sq) + 1
而不是 sq + 1
输出
find_next_square(144)
>>> 169
,
is_integer
是函数而不是变量,要调用它,您需要像任何函数调用一样使用 '()'
import math
def find_next_square(sq):
# Return the next square if sq is a square,-1 otherwise
if math.sqrt(sq).is_integer():
sqnext = sq + 1
if math.sqrt(sqnext).is_integer():
return sqnext
else:
return -1
尽管那样您仍然只会检查 sq
的以下数量,而不是下一个方块。您希望增加 sq
的平方根,然后返回其平方。
import math
def find_next_square(sq):
# Return the next square if sq is a square,-1 otherwise
found_sqrt = math.sqrt(sq)
if found_sqrt.is_integer():
sqrt_incr = found_sqrt + 1
return sqrt_incr * sqrt_incr
else:
return -1
就像其他答案说的,在你得到 sq
的平方根并且它确实是一个整数之后,你加 1 然后返回它的平方,从而得到下一个完美的平方。