A small helper function for the recursion, mainly to have a clean interface for the solution() function below. It should get called with the number of days (corresponding to the desired length of the 'prize strings'), and the initial values for the number of consecutive absent
(days: int, absent: int, late: int)
| 29 | |
| 30 | |
| 31 | def _calculate(days: int, absent: int, late: int) -> int: |
| 32 | """ |
| 33 | A small helper function for the recursion, mainly to have |
| 34 | a clean interface for the solution() function below. |
| 35 | |
| 36 | It should get called with the number of days (corresponding |
| 37 | to the desired length of the 'prize strings'), and the |
| 38 | initial values for the number of consecutive absent days and |
| 39 | number of total late days. |
| 40 | |
| 41 | >>> _calculate(days=4, absent=0, late=0) |
| 42 | 43 |
| 43 | >>> _calculate(days=30, absent=2, late=0) |
| 44 | 0 |
| 45 | >>> _calculate(days=30, absent=1, late=0) |
| 46 | 98950096 |
| 47 | """ |
| 48 | |
| 49 | # if we are absent twice, or late 3 consecutive days, |
| 50 | # no further prize strings are possible |
| 51 | if late == 3 or absent == 2: |
| 52 | return 0 |
| 53 | |
| 54 | # if we have no days left, and have not failed any other rules, |
| 55 | # we have a prize string |
| 56 | if days == 0: |
| 57 | return 1 |
| 58 | |
| 59 | # No easy solution, so now we need to do the recursive calculation |
| 60 | |
| 61 | # First, check if the combination is already in the cache, and |
| 62 | # if yes, return the stored value from there since we already |
| 63 | # know the number of possible prize strings from this point on |
| 64 | key = (days, absent, late) |
| 65 | if key in cache: |
| 66 | return cache[key] |
| 67 | |
| 68 | # now we calculate the three possible ways that can unfold from |
| 69 | # this point on, depending on our attendance today |
| 70 | |
| 71 | # 1) if we are late (but not absent), the "absent" counter stays as |
| 72 | # it is, but the "late" counter increases by one |
| 73 | state_late = _calculate(days - 1, absent, late + 1) |
| 74 | |
| 75 | # 2) if we are absent, the "absent" counter increases by 1, and the |
| 76 | # "late" counter resets to 0 |
| 77 | state_absent = _calculate(days - 1, absent + 1, 0) |
| 78 | |
| 79 | # 3) if we are on time, this resets the "late" counter and keeps the |
| 80 | # absent counter |
| 81 | state_ontime = _calculate(days - 1, absent, 0) |
| 82 | |
| 83 | prizestrings = state_late + state_absent + state_ontime |
| 84 | |
| 85 | cache[key] = prizestrings |
| 86 | return prizestrings |
| 87 | |
| 88 |