I am getting the error in the following code for the above stated problem using memoization please help me find the error and correct the code.
JavaScript
x
29
29
1
import sys
2
#sys.setrecursionlimit(10**5)
3
import math
4
cache={}
5
def m(n):
6
if n==0:
7
return 0
8
9
ans=sys.maxsize
10
root=int(math.sqrt(n))
11
for i in range(1,root+1):
12
13
nc=n-(i**2)
14
if cache[nc] not in cache:
15
sa=m(nc)
16
cache[nc]=sa
17
curr=1+sa
18
19
else:
20
curr=1+cache[nc]
21
22
ans=min(ans,curr)
23
24
return ans
25
26
27
28
print(m(int(input())))
29
Advertisement
Answer
It would help if you provided the full error output, which should include the line number and surrounding code. However, I suspect the issue lies in the following line:
JavaScript
1
2
1
if cache[nc] not in cache:
2
You’re checking whether the value of a dictionary key exists as a dictionary key. I assume you actually meant this (which will check whether a value is an existing dictionary key):
JavaScript
1
2
1
if nc not in cache:
2