在以下代码中获取 KeyError 以查找 "minimum number square to the number"
Getting KeyError in the following code to find "minimum number square to the number"
对于上述使用记忆的问题,我在以下代码中收到错误,请帮助我找到错误并更正代码。
import sys
#sys.setrecursionlimit(10**5)
import math
cache={}
def m(n):
if n==0:
return 0
ans=sys.maxsize
root=int(math.sqrt(n))
for i in range(1,root+1):
nc=n-(i**2)
if cache[nc] not in cache:
sa=m(nc)
cache[nc]=sa
curr=1+sa
else:
curr=1+cache[nc]
ans=min(ans,curr)
return ans
print(m(int(input())))
如果您提供完整的错误输出,这将有所帮助,其中应包括行号和周围的代码。但是,我怀疑问题出在以下行中:
if cache[nc] not in cache:
您正在检查字典键的值是否作为字典键存在。我假设你真的是这个意思(这将检查一个值是否是一个现有的字典键):
if nc not in cache:
对于上述使用记忆的问题,我在以下代码中收到错误,请帮助我找到错误并更正代码。
import sys
#sys.setrecursionlimit(10**5)
import math
cache={}
def m(n):
if n==0:
return 0
ans=sys.maxsize
root=int(math.sqrt(n))
for i in range(1,root+1):
nc=n-(i**2)
if cache[nc] not in cache:
sa=m(nc)
cache[nc]=sa
curr=1+sa
else:
curr=1+cache[nc]
ans=min(ans,curr)
return ans
print(m(int(input())))
如果您提供完整的错误输出,这将有所帮助,其中应包括行号和周围的代码。但是,我怀疑问题出在以下行中:
if cache[nc] not in cache:
您正在检查字典键的值是否作为字典键存在。我假设你真的是这个意思(这将检查一个值是否是一个现有的字典键):
if nc not in cache: