[Solved] How Python memoization works?
I'm trying to solve code coach Hofstadter's Q-Sequence. I write the code in standard recursion fashion with base case and return statement, it passes test case 1 & 2 and other doesn't. I check with Wikipedia and confirmed my code is correct with q(20) equals 12. Then I search Q&A for hints and found 2 possible solutions. One is set a higher recursion limit, and the other is memoization. I tried q(100) on my PC, and it keeps calculating after 5 mins so I forced it to stop. With memoization it outputs the result instantly, yet it still fails on test case 6 in code coach. Can anyone explain how memoization works in line by line style with q(3)? I used https://pythontutor.com to visualized the process but still don't understand what's going on. my_dict = {} def q(n): if n == 1 or n == 2: return 1 if n not in my_dict: my_dict[n] = q(n - q(n-1)) + q(n - (q(n-2)) return my_dict[n]