You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Here’s an optimized version of your program. The improvements focus on.
- Replacing `" ".join(str(i) for i in range(number))` with a much faster way by using a list comprehension and precomputing string representations up to the needed number only once.
- Removing redundant assignments (`j`) and unnecessary code that’s already explained as not needed.
- Using a helper to accelerate converting a range of integers to their string representations, leveraging `map(str, range(number))` over a generator, which is generally marginally faster and more memory-efficient for large values.
**Explanation of the change:**
`map(str, range(number))` is usually faster than a generator for this use case, because it avoids per-loop Python bytecode overhead and leverages the underlying C implementation. No unnecessary list/object creation or other overhead is involved. Caching logic and function signature are preserved.
If you want *maximum* speed for repeated numbers, consider precomputing all 1001 possible output strings once, but this gives negligible improvement with `lru_cache` and isn't necessary unless you want to drop the decorator (lru_cache is already very fast for this).
Let me know if you'd like an even faster, non-decorator, precomputed version!
0 commit comments