December 2023
Intermediate to advanced
504 pages
11h 43m
English
These are the solutions to the exercises found in the section Exercises.
The problem here is the function recursively calls itself twice each time it runs. Let’s make it so that it only calls itself once each time:
| | def add_until_100(array): |
| | if not array: |
| | return 0 |
| | |
| | sum_of_remaining_numbers = add_until_100(array[1:]) |
| | |
| | if array[0] + sum_of_remaining_numbers > 100: |
| | return sum_of_remaining_numbers |
| | else: |
| | return array[0] + sum_of_remaining_numbers |
Here is the memoized version:
| | def golomb(n, memo): |
| | if n == 1: |
| | return 1 |
| | |
| | if n not in memo: |
| | memo[n] = 1 + golomb(n - golomb(golomb(n - 1, memo), memo), memo) |
| | |
| | return memo[n] |
To accomplish memoization here, we need to make a key that ...
Read now
Unlock full access