Glasgow | 25-SDC-Nov | Nataliia Volkova | Sprint 2 | improve_with_caches#106
Glasgow | 25-SDC-Nov | Nataliia Volkova | Sprint 2 | improve_with_caches#106Nataliia74 wants to merge 3 commits intoCodeYourFuture:mainfrom
Conversation
| if total == 1 or len(coins) == 1: | ||
| result = 1 | ||
| cache[key] = result | ||
| return result |
There was a problem hiding this comment.
When total == 1 or len(coins) == 1 is true, the result may not be 1 if the last coin is not 1 (e.g. the initial list of coins given is different)
On the other hand, when len(coins) == 1, there is simple way to determine if the current total (any value) can be made by the coin value.
There was a problem hiding this comment.
Hello CJ Yuan, I understood that I can have 2 possible results, not just 1. So, the best founded solution is not to use recursion, but simple math to check if the total is divisible by that left type coin.
There was a problem hiding this comment.
What do you mean by 2 possible results? 0 or 1?
Yes, this approach:
simple math to check if the total is divisible by that left type coin
There was a problem hiding this comment.
Hello CJ Yuan, I mean 0 or 1. In this case, a better approach is to use math.
There was a problem hiding this comment.
Array creation is a relatively costly operation.
From line 41, we know coins can only be one of the following 9 arrays:
[200, 100, 50, 20, 10, 5, 2, 1]
[100, 50, 20, 10, 5, 2, 1]
[50, 20, 10, 5, 2, 1]
...
[1]
[]
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 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.
Eliminated slicing, which is costly and creates a new array every recursion, and also many duplicates; the tuple conversion was costly as well. Changed by exchanging the tuple at the index an array.
| cache = {} | ||
| coins = [1, 2, 5, 10, 20, 50, 100, 200] |
There was a problem hiding this comment.
Should you need to avoid introducing variables in the global scope, you can consider:
- Declare them in
ways_to_make_change() - Define
ways_to_make_change_helper()as an inner function ofways_to_make_change(). Inner function can access the variables in the outer scope.
Learners, PR Template
Self checklist
Changelist
Improve code with caches 11