London | 26-SDC-March | Zobeir Rigi | Sprint 2 | Improve code with caches - #209
London | 26-SDC-March | Zobeir Rigi | Sprint 2 | Improve code with caches#209Zobeir-Rigi wants to merge 4 commits into
Conversation
| @@ -1,4 +1,10 @@ | |||
| cache = {0: 0, 1: 1} | |||
There was a problem hiding this comment.
Could you look into an approach that doesn't require keeping the cache in the global scope?
There was a problem hiding this comment.
Could you look into an approach that doesn't require keeping the cache in the global scope?
I updated the implementation so the cache is no longer stored in the global scope.
| ways += ways_to_make_change_helper( | ||
| total - total_from_coins, | ||
| coins[coin_index + 1:] | ||
| ) |
There was a problem hiding this comment.
Array and tuple creations are relatively costly operations.
We could further improve the performance if we can
- avoid repeatedly creating the same sub-arrays at line 41 (e.g. use another cache), and
- create key (on line 19) as (total, a_unique_integer_identifying_the_subarray) instead of as (total, tuple of coins)
- There are only a small number of different subarrays. We can easily assign each subarray a unique integer.
There was a problem hiding this comment.
Array and tuple creations are relatively costly operations.
We could further improve the performance if we can
avoid repeatedly creating the same sub-arrays at line 41 (e.g. use another cache), and
create key (on line 19) as (total, a_unique_integer_identifying_the_subarray) instead of as (total, tuple of coins)
- There are only a small number of different subarrays. We can easily assign each subarray a unique integer.
Thanks, I refactored the solution to avoid repeatedly creating sublists and tuples. The implementation now uses a fixed coin list and passes a start index through the recursive calls, which allows the cache key to be (total, start_index) and reduces unnecessary allocations.
|
Changes look good. |
I originally completed all the Sprint 2 exercises in one PR, but the validation expected separate PRs for each issue. This PR contains only the "Improve code with caches" exercise.
Added memoisation/caching to improve the performance of:
All provided tests pass.