Sheffield | 25-SDC-Nov | Hassan Osman | Sprint 2 | Improve code with caches#130
Sheffield | 25-SDC-Nov | Hassan Osman | Sprint 2 | Improve code with caches#130HassanOHOsman wants to merge 21 commits intoCodeYourFuture:mainfrom
Conversation
…ing its value (result)
…thus return it's associated value
…me (total, coins) combination, we can reuse it.
| @@ -29,4 +26,7 @@ def ways_to_make_change_helper(total: int, coins: List[int]) -> int: | |||
| intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:]) | |||
| ways += intermediate | |||
| count_of_coin += 1 | |||
There was a problem hiding this comment.
Array creation is a relatively costly operation.
From line 26, 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]
...
[]
We could further improve the performance if we can
- avoid repeatedly creating the same sub-arrays at line 26 (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.
…e a hard-coded list with all the coins so that we can refer to any using their index
…dentify a subarray we're using
| @@ -1,32 +1,38 @@ | |||
| from typing import List | |||
|
|
|||
| coins = [200, 100, 50, 20, 10, 5, 2, 1] | |||
There was a problem hiding this comment.
-
If this is to be used as a constant, best practice is to name it with all uppercase letters.
-
We could also keep the
coinsarray in the parameter. Arrays are pass by reference to a function so the overhead is negligible.
| if key in cache: | ||
| return cache[key] | ||
|
|
||
| if total == 0: | ||
| return 1 | ||
|
|
||
|
|
||
| if coin_index == len(coins): | ||
| return 0 |
There was a problem hiding this comment.
Note: Even though key construction and dictionary lookup are O(1) operations, they are still relatively costly than some simple numerical computation or comparisons (code on lines 18 and 22).
This is unrelated to cache, but if you swap the code on lines 18-23 with the code on lines 13-16, you can probably notice some slight improvement in performance.
Self checklist
In this pull request, I introduced caching (memoisation) to Fibonacci and Making Change directories to make the implementation more efficient.