Calculate the length of the chain of non-repeating terms starting with n. Previous is a set containing the previous member of the chain. >>> chain_length(10101) 11 >>> chain_length(555) 20 >>> chain_length(178924) 39
(n: int, previous: set | None = None)
| 71 | |
| 72 | |
| 73 | def chain_length(n: int, previous: set | None = None) -> int: |
| 74 | """ |
| 75 | Calculate the length of the chain of non-repeating terms starting with n. |
| 76 | Previous is a set containing the previous member of the chain. |
| 77 | >>> chain_length(10101) |
| 78 | 11 |
| 79 | >>> chain_length(555) |
| 80 | 20 |
| 81 | >>> chain_length(178924) |
| 82 | 39 |
| 83 | """ |
| 84 | previous = previous or set() |
| 85 | if n in CHAIN_LENGTH_CACHE: |
| 86 | return CHAIN_LENGTH_CACHE[n] |
| 87 | next_number = sum_digit_factorials(n) |
| 88 | if next_number in previous: |
| 89 | CHAIN_LENGTH_CACHE[n] = 0 |
| 90 | return 0 |
| 91 | else: |
| 92 | previous.add(n) |
| 93 | ret = 1 + chain_length(next_number, previous) |
| 94 | CHAIN_LENGTH_CACHE[n] = ret |
| 95 | return ret |
| 96 | |
| 97 | |
| 98 | def solution(num_terms: int = 60, max_start: int = 1000000) -> int: |
no test coverage detected