NW | 26-SDC-Mar | TzeMing Ho | Sprint 2 | improve with caches#171
NW | 26-SDC-Mar | TzeMing Ho | Sprint 2 | improve with caches#171TzeMingHo wants to merge 4 commits into
Conversation
| def fibonacci(n, cache=None): | ||
| if cache == None: | ||
| cache={0:0, 1:1} | ||
| if n in cache: | ||
| return cache[n] | ||
| else: | ||
| value = fibonacci(n - 1, cache) + fibonacci(n - 2, cache) | ||
| cache[n] = value | ||
| return value |
There was a problem hiding this comment.
Could you research different approaches to make the cache reusable across multiple function calls (instead of repopulating it from the beginning)? Ideally, the approach does not involve using any global variable.
There was a problem hiding this comment.
I tried to use attributes. Is it a better way?
There was a problem hiding this comment.
Your implementation looks good.
Note: there is a much faster way to figure out how many ways we could make change when there is only 1 coin left to consider.
There was a problem hiding this comment.
So, when coin_index hits 7, which leads to coin value 1, we can simply return 1, right? No matter what the total is left, with coin value 1, it always gets 1 way.
There was a problem hiding this comment.
Correct.
I see that you have also figured out how to compute number of ways to make change when there is one coin left using %. Nice!
|
Changes look great. Well done. |
Learners, PR Template
Self checklist
Changelist
In the making_change exercise, I have to discard the for loop and the while loop because it was difficult for me to understand what was happening. By implementing the take or leave the coin logic with coin_index, it explores the combinations with different starting coins. When total hits 0, it finds a way.